Реализовать лабораторную 7
This commit is contained in:
@@ -18,3 +18,5 @@ __pycache__
|
|||||||
node_modules
|
node_modules
|
||||||
evidence
|
evidence
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
**/__pycache__
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
*.sh text eol=lf
|
||||||
@@ -1,18 +1,17 @@
|
|||||||
## Лабораторная 7
|
## Лабораторная 7
|
||||||
|
|
||||||
Автор / группа: TODO
|
Автор и группа — Samodurov Nikita, bpi2303.
|
||||||
Целевая оценка (3/4/5): TODO
|
Целевая оценка — 4.
|
||||||
Трек 5, если заявлен: TODO
|
|
||||||
|
|
||||||
Что реализовано и что перенесено: TODO
|
Добавлены HTTPS ingress, mTLS и разрешённые service identities для внутренних связей,
|
||||||
Команды запуска из чистого clone: TODO
|
scoped OpenBao cert-auth policies, Argon2id и общий login rate limit.
|
||||||
Результаты проверок и ссылка на REPORT.md: TODO
|
Контейнеры приложений работают non-root, read_only и без capabilities.
|
||||||
Ограничения / известные ошибки: TODO
|
Проверены отрицательные TLS/ACL сценарии, rehash, ротация рабочего secret и leaf,
|
||||||
Источники и использование ИИ: TODO
|
отзыв старой identity, token expiry и sealed OpenBao.
|
||||||
|
|
||||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
Запуск описан в [REPORT.md](REPORT.md).
|
||||||
- [ ] Контракт и публичные тесты не ослаблены.
|
[Модель угроз](THREAT_MODEL.md) · [Trust matrix](contracts/trust-matrix.md).
|
||||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
[Проверки](evidence/security.txt) · [Ротация](evidence/rotation.txt) · [Аудит](SCAN_TRIAGE.md).
|
||||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
|
||||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
Источники — контракт курса и официальная документация OpenBao, OpenTelemetry и PostgreSQL.
|
||||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
Использование ИИ — консультации и проверки ИИ.
|
||||||
|
|||||||
@@ -12,5 +12,29 @@ jobs:
|
|||||||
python-version: '3.12'
|
python-version: '3.12'
|
||||||
- run: python -m pip install -r requirements-dev.txt
|
- run: python -m pip install -r requirements-dev.txt
|
||||||
- run: make check validate PYTHON=python
|
- run: make check validate PYTHON=python
|
||||||
# This job validates the skeleton, not a student solution.
|
application:
|
||||||
# Add build, readiness and make test in a separate application job.
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 25
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.13'
|
||||||
|
- name: Build local stack
|
||||||
|
run: |
|
||||||
|
chmod +x scripts/restart.sh scripts/stop-one.sh
|
||||||
|
python -m pip install -r requirements-bootstrap.txt
|
||||||
|
python scripts/start.py
|
||||||
|
- name: Verify application and failure scenarios
|
||||||
|
run: |
|
||||||
|
make test BASE_URL=https://localhost:18443 CA_FILE=secrets/operator/ca.pem
|
||||||
|
make test-security BASE_URL=https://localhost:18443 CA_FILE=secrets/operator/ca.pem
|
||||||
|
docker compose run --rm --no-deps security-check
|
||||||
|
python student-tests/check_rotation.py
|
||||||
|
python student-tests/check_grafana.py
|
||||||
|
- name: Show status on failure
|
||||||
|
if: failure()
|
||||||
|
run: docker compose ps -a
|
||||||
|
- name: Stop stack
|
||||||
|
if: always()
|
||||||
|
run: docker compose stop
|
||||||
|
|||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
FROM python:3.13.5-slim-bookworm@sha256:4c2cf9917bd1cbacc5e9b07320025bdb7cdf2df7b0ceaccb55e9dd7e30987419
|
||||||
|
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir pip==26.2 && pip install --no-cache-dir -r requirements.txt
|
||||||
|
COPY migrations/ ./migrations/
|
||||||
|
COPY src/ ./src/
|
||||||
|
USER 10001:10001
|
||||||
|
EXPOSE 8080
|
||||||
|
HEALTHCHECK --interval=3s --timeout=3s --start-period=5s --retries=4 \
|
||||||
|
CMD ["python", "-c", "import os,urllib.request; urllib.request.urlopen('http://127.0.0.1:'+os.getenv('APP_PORT','8080')+'/health/ready',timeout=2).close()"]
|
||||||
|
CMD ["python", "src/server.py"]
|
||||||
@@ -1,37 +1,102 @@
|
|||||||
# Отчёт — лабораторная 7
|
# Отчёт — лабораторная 7
|
||||||
|
|
||||||
- Автор, группа: TODO
|
Автор и группа — Samodurov Nikita, bpi2303.
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
Целевая оценка — 4.
|
||||||
- Commit/PR: TODO после публикации
|
Использование ИИ — консультации и проверки ИИ.
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Нужны Docker Engine, Compose v2 и Python 3.13 с bootstrap-зависимостями.
|
||||||
|
|
||||||
## Архитектура и решения
|
python -m pip install -r requirements-bootstrap.txt
|
||||||
|
python scripts/start.py
|
||||||
|
python tests/smoke.py --base-url https://localhost:18443 --ca-file secrets/operator/ca.pem
|
||||||
|
python tests/security.py --base-url https://localhost:18443 --ca-file secrets/operator/ca.pem
|
||||||
|
docker compose run --rm --no-deps security-check
|
||||||
|
python student-tests/check_rotation.py
|
||||||
|
python student-tests/check_grafana.py
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
В Windows перед проверками задайте PYTHONUTF8=1.
|
||||||
|
Для check_rotation.py используется https://localhost:18443, CA из secrets/operator.
|
||||||
|
Для публичных resilience-проверок задайте BASE_URL и CA_FILE аналогично smoke.
|
||||||
|
В Linux action scripts — scripts/restart.sh и scripts/stop-one.sh,
|
||||||
|
в PowerShell — соответствующие .cmd.
|
||||||
|
|
||||||
## Доказательства критериев
|
Внешние интерфейсы опубликованы на loopback хоста. API доступен по HTTPS на 18443,
|
||||||
|
Grafana на 13007, OpenBao на 18207. Пароль Grafana находится в
|
||||||
|
secrets/grafana_password, имя пользователя admin. Проверяйте локальный CA.
|
||||||
|
Команда docker compose stop сохраняет данные, docker compose down -v намеренно
|
||||||
|
удаляет учебные тома.
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
## Trust и bootstrap
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
Из ЛР 6 перенесены API-реплики, PostgreSQL, Redis, S3, очередь, worker и telemetry.
|
||||||
|
[Матрица доверия](contracts/trust-matrix.md) описывает каждую связь и идентичность.
|
||||||
|
[Модель угроз](THREAT_MODEL.md) связывает угрозы с отрицательными проверками.
|
||||||
|
|
||||||
## Эксперименты и отказы
|
Оператор создаёт CA/leaf и локальные secrets. OpenBao работает в server mode
|
||||||
|
с постоянным file storage. Init/unseal share и root token остаются в operator-файле.
|
||||||
|
Его каталог закрыт родительским secrets и не монтируется в приложения.
|
||||||
|
Сервис аутентифицируется сертификатом и читает только собственный KV path.
|
||||||
|
Token действует 60 с с максимумом 120 с. Для проверки expiry использован TTL 2 с.
|
||||||
|
После обычного рестарта API повторно аутентифицируется своим leaf certificate.
|
||||||
|
После рестарта самого OpenBao оператор выполняет scripts/bao_operator.py.
|
||||||
|
Публичный restart hook выполняет этот operator-шаг явно на хосте.
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Native PostgreSQL принимает только TLS для сетевых соединений. API, worker и dispatcher
|
||||||
|
имеют разные DB roles. Для компонентов с plaintext listener используется TLS bridge
|
||||||
|
в том же network namespace и loopback hop. Bridge проверяет CA, SAN allowlist,
|
||||||
|
отозванные serial и разрешённые HTTP-методы. Входной API-порт доступен только на loopback.
|
||||||
|
API S3 PUT ограничен staging/UUID, worker пишет готовые варианты.
|
||||||
|
Redis имеет разные producer/consumer ACL. Grafana читает источники через mTLS.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
## Пароли и лимиты
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| TODO | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
Argon2id использует 19 456 KiB, t=2, p=1 и библиотечную случайную соль.
|
||||||
|
Успешный вход обновляет старый scrypt hash и параметры Argon2id при необходимости.
|
||||||
|
Общий PostgreSQL limit допускает десять входов на username за минуту.
|
||||||
|
После превышения API отвечает 429 и Retry-After=60 через любую реплику.
|
||||||
|
Число одновременных password operations ограничено двумя на процесс.
|
||||||
|
Измерение 20 циклов hash+verify дало p50 0,0423 с, p95 0,0674 с,
|
||||||
|
пиковый RSS benchmark-процесса 40 701 952 байта.
|
||||||
|
Повтор измерения — benchmark_passwords.py в security-check.
|
||||||
|
Контейнер API ограничен 640 MiB. Размеры изображения и время worker ограничены
|
||||||
|
унаследованным контрактом pipeline.
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
## Ротация и отзыв
|
||||||
|
|
||||||
|
python scripts/rotate.py secret
|
||||||
|
python scripts/rotate.py certificate
|
||||||
|
|
||||||
|
Первый сценарий обновляет DB password, KV и переподключает API.
|
||||||
|
Второй заменяет leaf api-a, публикует CRL OpenBao и denylist TLS bridges.
|
||||||
|
Образы при ротации не пересобираются. Проверка старых credentials использует
|
||||||
|
новые соединения. Исходная пользовательская сессия остаётся действительной.
|
||||||
|
Для продления leaf после 24 часов оператор запускает pki.py rotate SERVICE
|
||||||
|
и перезапускает сервис с его TLS bridge.
|
||||||
|
|
||||||
|
Проверка sealed OpenBao подтверждает отказ выдачи новых credentials.
|
||||||
|
Уже открытые DB connections могут продолжать работать. Сервис не переключается
|
||||||
|
на локальный root token. Ротация рабочего secret требует переподключения клиента,
|
||||||
|
это действие включено в rotate.py.
|
||||||
|
|
||||||
|
## Проверки и аудит
|
||||||
|
|
||||||
|
Публичный HTTPS smoke, недоверенный TLS и внутренние отрицательные проверки
|
||||||
|
сохранены в evidence. Проверены отсутствие клиентского cert, чужой CA,
|
||||||
|
запрещённая identity при доверенном CA, DB role, S3 prefix, OpenBao policy,
|
||||||
|
общий login limit, rehash и отсутствие тестовых секретов в telemetry.
|
||||||
|
Lifecycle-проверки сохранены в evidence/rotation.txt.
|
||||||
|
Чистый bootstrap, команды и результаты перечислены в [evidence/README.md](evidence/README.md).
|
||||||
|
|
||||||
|
Аудит выполняется python scripts/audit.py. Первоначальные advisory разобраны
|
||||||
|
в [SCAN_TRIAGE.md](SCAN_TRIAGE.md). В финальном scan 33 Python-пакетов
|
||||||
|
известных advisory не обнаружено.
|
||||||
|
|
||||||
|
## Ограничения
|
||||||
|
|
||||||
|
CA/unseal являются operator trust boundary. Один узел PostgreSQL, S3 и broker
|
||||||
|
не защищает от потери диска или машины. Нативные пакеты остальных образов
|
||||||
|
не покрыты Python dependency scan. Stateful компоненты используют writable тома,
|
||||||
|
приложения и TLS bridges работают read_only с drop capabilities и tmpfs.
|
||||||
|
Одноразовый bootstrap владельца OpenBao-тома использует только CHOWN.
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Аудит зависимостей
|
||||||
|
|
||||||
|
Проверка выполнена pip-audit 2.9.0 по фактически установленным пакетам
|
||||||
|
/usr/local/lib/python3.13/site-packages в финальном Linux-образе.
|
||||||
|
Исходный scan обнаружил 76 advisory в пяти пакетах. Все пять обновлены.
|
||||||
|
|
||||||
|
- cryptography 46.0.4 → 50.0.0. В исходной версии 7 advisory, после обновления 0.
|
||||||
|
- opentelemetry-api 1.34.1 → 1.45.2. В исходной версии 2 advisory, после обновления 0.
|
||||||
|
- pillow 12.2.0 → 13.0.0. В исходной версии 55 advisory, после обновления 0.
|
||||||
|
- pip 25.1.1 → 26.2. В исходной версии 6 advisory, после обновления 0.
|
||||||
|
- urllib3 2.5.0 → 2.8.0. В исходной версии 6 advisory, после обновления 0.
|
||||||
|
|
||||||
|
Pillow используется при приёме и обработке недоверенных изображений.
|
||||||
|
Часть advisory относится к форматам шрифтов/просмотру на Windows, которые
|
||||||
|
приложение не вызывает. Допустимые входные форматы ограничены PNG/JPEG,
|
||||||
|
но обновлена библиотека целиком, включая декодеры.
|
||||||
|
|
||||||
|
OpenTelemetry разбирает входящие W3C trace headers. ReDoS в propagator применим
|
||||||
|
к HTTP-пути, поэтому API, SDK и exporter обновлены вместе.
|
||||||
|
urllib3 используется S3-клиентом и exporter, поэтому исправления HTTP parsing,
|
||||||
|
redirect и streaming применены к установленной библиотеке.
|
||||||
|
cryptography используется bootstrap PKI. Исправлены зависимости инструментов
|
||||||
|
оператора, хотя приложение не выполняет PKCS7 decrypt.
|
||||||
|
pip работает на стадии сборки, обновлён также установленный build tool.
|
||||||
|
|
||||||
|
В повторном scan проверены 33 пакета, известных advisory не обнаружено.
|
||||||
|
[До обновления](evidence/dependency-audit-before.json) и
|
||||||
|
[финальный JSON](evidence/dependency-audit.json) сохранены для воспроизведения.
|
||||||
|
|
||||||
|
Команда сканирования запускает pip-audit в одноразовом контейнере и задаёт
|
||||||
|
writable-кэш /tmp/cache. База advisory соответствует моменту запуска 30.11.2026.
|
||||||
|
Это аудит Python-зависимостей. Нативные пакеты ОС и отдельные образы PostgreSQL,
|
||||||
|
SeaweedFS, Redis, OpenBao и Grafana этим результатом не покрыты.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Модель угроз
|
||||||
|
|
||||||
|
Активы — сообщения и вложения, сессии, password hashes, сервисные credentials,
|
||||||
|
приватные ключи, подтверждённые задания, данные наблюдаемости.
|
||||||
|
Акторы — участник чата, посторонний пользователь, другой сервис с доверенным
|
||||||
|
сертификатом, оператор и клиент без сертификата.
|
||||||
|
|
||||||
|
| Угроза | Контроль | Отрицательная проверка |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Подмена ingress или MITM | CA + hostname/SAN | чужой CA и неправильный hostname |
|
||||||
|
| Обход LB прямым запросом | API bind loopback, TLS bridge с SAN allowlist | api:8080 недоступен, без cert и foreign cert denied |
|
||||||
|
| Чужой чат/вложение | Bearer и членство в PostgreSQL | outsider metadata/content 404 |
|
||||||
|
| Кража сервисных секретов через OpenBao | cert auth и отдельные policy paths | API не читает worker path и sys/policies |
|
||||||
|
| Компрометация worker с доступом к БД | раздельная DB role | worker DELETE users denied |
|
||||||
|
| Вставка задания consumer-ом | Redis ACL и broker mTLS | worker XADD denied, чужая identity denied |
|
||||||
|
| Подмена telemetry другим сервисом | Collector mTLS allowlist | foreign и untrusted client cert denied |
|
||||||
|
| Перезапись оригинала из API | S3 gateway identity и staging-prefix | API PUT final prefix denied |
|
||||||
|
| Перебор паролей и KDF DoS | общий DB limit, Argon2id, два hash slots | 429/Retry-After через обе реплики, benchmark |
|
||||||
|
| Долгоживущий украденный ключ | leaf TTL, CRL, proxy denylist, token expiry | check_rotation.py выполняет новые соединения со старым cert/паролем |
|
||||||
|
| Утечка содержимого в telemetry | шаблоны route и отсутствие body/headers | тестовый password/session token отсутствуют в логах |
|
||||||
|
| Огромное/повреждённое изображение | byte/pixel/time/CPU/RAM лимиты worker | унаследованный контракт, публичный smoke и тесты pipeline |
|
||||||
|
|
||||||
|
Стена доверия оператора включает CA key и init/unseal файл. Её компрометация
|
||||||
|
даёт административные права. Сервисы получают только свои TLS-каталоги.
|
||||||
|
Контейнер security-check — отдельный operator test harness с профилем tools,
|
||||||
|
имеет тестовые клиентские сертификаты и не запускается обычным compose up.
|
||||||
|
|
||||||
|
Один экземпляр БД, broker и S3 не защищает от потери их дисков или хоста.
|
||||||
|
Резервирование узлов находится за пределами этой лабораторной.
|
||||||
+767
@@ -0,0 +1,767 @@
|
|||||||
|
services:
|
||||||
|
db:
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 384m
|
||||||
|
image: postgres:17.5-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: messenger
|
||||||
|
POSTGRES_DB: messenger
|
||||||
|
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
|
||||||
|
secrets:
|
||||||
|
- db_password
|
||||||
|
volumes:
|
||||||
|
- pgdata:/var/lib/postgresql/data
|
||||||
|
- ./secrets/tls/db:/tls:ro
|
||||||
|
- ./infra/db-entrypoint.sh:/bootstrap.sh:ro
|
||||||
|
- ./infra/pg_hba.conf:/bootstrap/pg_hba.conf:ro
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
- CMD-SHELL
|
||||||
|
- pg_isready -U messenger -d messenger
|
||||||
|
interval: 2s
|
||||||
|
timeout: 2s
|
||||||
|
retries: 20
|
||||||
|
command:
|
||||||
|
- postgres
|
||||||
|
- -c
|
||||||
|
- ssl=on
|
||||||
|
- -c
|
||||||
|
- ssl_cert_file=/tmp/db-tls/cert.pem
|
||||||
|
- -c
|
||||||
|
- ssl_key_file=/tmp/db-tls/key.pem
|
||||||
|
- -c
|
||||||
|
- hba_file=/bootstrap/pg_hba.conf
|
||||||
|
entrypoint:
|
||||||
|
- /bin/sh
|
||||||
|
- /bootstrap.sh
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
cap_add:
|
||||||
|
- CHOWN
|
||||||
|
- DAC_OVERRIDE
|
||||||
|
- FOWNER
|
||||||
|
- SETUID
|
||||||
|
- SETGID
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
cache:
|
||||||
|
cpus: 0.25
|
||||||
|
mem_limit: 96m
|
||||||
|
image: redis:7.4.3-alpine
|
||||||
|
command:
|
||||||
|
- redis-server
|
||||||
|
- --bind
|
||||||
|
- 127.0.0.1
|
||||||
|
- --aclfile
|
||||||
|
- /run/acl/cache.acl
|
||||||
|
volumes:
|
||||||
|
- ./secrets/cache.acl:/run/acl/cache.acl:ro
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
cap_add:
|
||||||
|
- CHOWN
|
||||||
|
- DAC_OVERRIDE
|
||||||
|
- FOWNER
|
||||||
|
- SETUID
|
||||||
|
- SETGID
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
migrate:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 640m
|
||||||
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
CURSOR_KEY_FILE: /run/secrets/cursor_key
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
|
S3_ENDPOINT: https://s3:9002
|
||||||
|
APP_HOST: 127.0.0.1
|
||||||
|
secrets:
|
||||||
|
- database_url
|
||||||
|
- cache_url
|
||||||
|
- cursor_key
|
||||||
|
- broker_url
|
||||||
|
build: .
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/migrate.py
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
read_only: true
|
||||||
|
security_opt: &id001
|
||||||
|
- no-new-privileges:true
|
||||||
|
cap_drop: &id002
|
||||||
|
- ALL
|
||||||
|
tmpfs: &id003
|
||||||
|
- /tmp:rw,nosuid,nodev,size=32m
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/migrate:/tls:ro
|
||||||
|
s3:
|
||||||
|
image: chrislusf/seaweedfs:3.97
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 512m
|
||||||
|
command:
|
||||||
|
- server
|
||||||
|
- -dir=/data
|
||||||
|
- -s3
|
||||||
|
- -s3.port=9000
|
||||||
|
- -s3.config=/run/secrets/s3_config
|
||||||
|
- -s3.ip.bind=127.0.0.1
|
||||||
|
- -ip=127.0.0.1
|
||||||
|
- -ip.bind=127.0.0.1
|
||||||
|
secrets:
|
||||||
|
- s3_config
|
||||||
|
volumes:
|
||||||
|
- objects:/data
|
||||||
|
networks:
|
||||||
|
- storage
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
s3-init:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 640m
|
||||||
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
S3_ADMIN_ACCESS_KEY_FILE: /run/secrets/s3_admin_access_key
|
||||||
|
S3_ADMIN_SECRET_KEY_FILE: /run/secrets/s3_admin_secret_key
|
||||||
|
S3_ENDPOINT: https://s3:9002
|
||||||
|
APP_HOST: 127.0.0.1
|
||||||
|
secrets:
|
||||||
|
- s3_admin_access_key
|
||||||
|
- s3_admin_secret_key
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/bootstrap_s3.py
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
depends_on:
|
||||||
|
s3-tls:
|
||||||
|
condition: service_started
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/s3-init:/tls:ro
|
||||||
|
networks:
|
||||||
|
- default
|
||||||
|
- storage
|
||||||
|
broker:
|
||||||
|
image: redis:7.4.3-alpine
|
||||||
|
command:
|
||||||
|
- redis-server
|
||||||
|
- --bind
|
||||||
|
- 127.0.0.1
|
||||||
|
- --aclfile
|
||||||
|
- /run/acl/broker.acl
|
||||||
|
- --appendonly
|
||||||
|
- 'yes'
|
||||||
|
- --appendfsync
|
||||||
|
- always
|
||||||
|
- --save
|
||||||
|
- ''
|
||||||
|
volumes:
|
||||||
|
- brokerdata:/data
|
||||||
|
- ./secrets/broker.acl:/run/acl/broker.acl:ro
|
||||||
|
mem_limit: 128m
|
||||||
|
cpus: 0.5
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
cap_add:
|
||||||
|
- CHOWN
|
||||||
|
- DAC_OVERRIDE
|
||||||
|
- FOWNER
|
||||||
|
- SETUID
|
||||||
|
- SETGID
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
dispatcher:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 640m
|
||||||
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
CURSOR_KEY_FILE: /run/secrets/cursor_key
|
||||||
|
CRASH_BEFORE_PUBLISH: ${CRASH_BEFORE_PUBLISH:-0}
|
||||||
|
S3_ENDPOINT: https://s3:9002
|
||||||
|
APP_HOST: 127.0.0.1
|
||||||
|
SERVICE_ID: dispatcher
|
||||||
|
secrets: []
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/dispatcher.py
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
depends_on:
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
broker:
|
||||||
|
condition: service_started
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/dispatcher:/tls:ro
|
||||||
|
worker:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 640m
|
||||||
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
CURSOR_KEY_FILE: /run/secrets/cursor_key
|
||||||
|
CRASH_AFTER_OBJECTS: ${CRASH_AFTER_OBJECTS:-0}
|
||||||
|
S3_ENDPOINT: https://s3:9002
|
||||||
|
APP_HOST: 127.0.0.1
|
||||||
|
SERVICE_ID: worker
|
||||||
|
secrets: []
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/worker.py
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
depends_on:
|
||||||
|
s3-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
broker:
|
||||||
|
condition: service_started
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/worker:/tls:ro
|
||||||
|
networks:
|
||||||
|
- default
|
||||||
|
- storage
|
||||||
|
api-a:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 640m
|
||||||
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
CURSOR_KEY_FILE: /run/secrets/cursor_key
|
||||||
|
INSTANCE_ID: api-a
|
||||||
|
S3_ENDPOINT: https://s3:9002
|
||||||
|
APP_HOST: 127.0.0.1
|
||||||
|
SERVICE_ID: api-a
|
||||||
|
secrets: []
|
||||||
|
depends_on: &id004
|
||||||
|
s3-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
cache:
|
||||||
|
condition: service_started
|
||||||
|
stop_grace_period: 8s
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/api-a:/tls:ro
|
||||||
|
networks:
|
||||||
|
- default
|
||||||
|
- storage
|
||||||
|
api-b:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 640m
|
||||||
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
CURSOR_KEY_FILE: /run/secrets/cursor_key
|
||||||
|
INSTANCE_ID: api-b
|
||||||
|
S3_ENDPOINT: https://s3:9002
|
||||||
|
APP_HOST: 127.0.0.1
|
||||||
|
SERVICE_ID: api-b
|
||||||
|
secrets: []
|
||||||
|
depends_on: *id004
|
||||||
|
stop_grace_period: 8s
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/api-b:/tls:ro
|
||||||
|
networks:
|
||||||
|
- default
|
||||||
|
- storage
|
||||||
|
lb:
|
||||||
|
image: haproxy:3.0.11-alpine
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 96m
|
||||||
|
ports:
|
||||||
|
- 127.0.0.1:18443:8443
|
||||||
|
volumes:
|
||||||
|
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||||
|
- ./secrets/tls/lb:/tls:ro
|
||||||
|
depends_on:
|
||||||
|
api-a:
|
||||||
|
condition: service_healthy
|
||||||
|
api-b:
|
||||||
|
condition: service_healthy
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
otel-collector:
|
||||||
|
image: otel/opentelemetry-collector-contrib:0.127.0
|
||||||
|
command:
|
||||||
|
- --config=/etc/otel/config.yaml
|
||||||
|
mem_limit: 192m
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel.yaml:/etc/otel/config.yaml:ro
|
||||||
|
- ./secrets/tls/otel-collector:/tls:ro
|
||||||
|
cpus: 0.5
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
prometheus:
|
||||||
|
image: prom/prometheus:v3.4.1
|
||||||
|
volumes:
|
||||||
|
- ./infra/prometheus.yaml:/etc/prometheus/prometheus.yml:ro
|
||||||
|
- ./infra/alerts.yaml:/etc/prometheus/alerts.yaml:ro
|
||||||
|
- metricsdata:/prometheus
|
||||||
|
- ./secrets/tls/prometheus:/tls:ro
|
||||||
|
mem_limit: 256m
|
||||||
|
command:
|
||||||
|
- --config.file=/etc/prometheus/prometheus.yml
|
||||||
|
- --web.listen-address=127.0.0.1:9090
|
||||||
|
cpus: 0.5
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
loki:
|
||||||
|
image: grafana/loki:3.5.1
|
||||||
|
command:
|
||||||
|
- -config.file=/etc/loki/config.yaml
|
||||||
|
volumes:
|
||||||
|
- ./infra/loki.yaml:/etc/loki/config.yaml:ro
|
||||||
|
- logsdata:/loki
|
||||||
|
- ./secrets/tls/loki:/tls:ro
|
||||||
|
mem_limit: 256m
|
||||||
|
cpus: 0.5
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
tempo:
|
||||||
|
image: grafana/tempo:2.8.0
|
||||||
|
command:
|
||||||
|
- -config.file=/etc/tempo.yaml
|
||||||
|
volumes:
|
||||||
|
- ./infra/tempo.yaml:/etc/tempo.yaml:ro
|
||||||
|
- tracesdata:/var/tempo
|
||||||
|
- ./secrets/tls/tempo:/tls:ro
|
||||||
|
mem_limit: 256m
|
||||||
|
cpus: 0.5
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
grafana:
|
||||||
|
image: grafana/grafana:12.0.2
|
||||||
|
ports:
|
||||||
|
- 127.0.0.1:13007:3000
|
||||||
|
volumes:
|
||||||
|
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||||
|
- grafanadata:/var/lib/grafana
|
||||||
|
- ./infra/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro
|
||||||
|
- ./secrets/grafana-datasources.yaml:/etc/grafana/provisioning/datasources/sources.yaml:ro
|
||||||
|
- ./secrets/grafana_password:/run/grafana_password:ro
|
||||||
|
- ./secrets/tls/grafana:/tls:ro
|
||||||
|
mem_limit: 256m
|
||||||
|
environment:
|
||||||
|
GF_SERVER_PROTOCOL: https
|
||||||
|
GF_SERVER_CERT_FILE: /tls/cert.pem
|
||||||
|
GF_SERVER_CERT_KEY: /tls/key.pem
|
||||||
|
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/grafana_password
|
||||||
|
cpus: 0.5
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
api-a-tls:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
network_mode: service:api-a
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/tls_bridge.py
|
||||||
|
- /bridge/api-a-tls.json
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/api-a:/tls:ro
|
||||||
|
- ./infra/tls:/bridge:ro
|
||||||
|
depends_on:
|
||||||
|
api-a:
|
||||||
|
condition: service_started
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.25
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
api-b-tls:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
network_mode: service:api-b
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/tls_bridge.py
|
||||||
|
- /bridge/api-b-tls.json
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/api-b:/tls:ro
|
||||||
|
- ./infra/tls:/bridge:ro
|
||||||
|
depends_on:
|
||||||
|
api-b:
|
||||||
|
condition: service_started
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.25
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
broker-tls:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
network_mode: service:broker
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/tls_bridge.py
|
||||||
|
- /bridge/broker-tls.json
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/broker:/tls:ro
|
||||||
|
- ./infra/tls:/bridge:ro
|
||||||
|
depends_on:
|
||||||
|
broker:
|
||||||
|
condition: service_started
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.25
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
cache-tls:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
network_mode: service:cache
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/tls_bridge.py
|
||||||
|
- /bridge/cache-tls.json
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/cache:/tls:ro
|
||||||
|
- ./infra/tls:/bridge:ro
|
||||||
|
depends_on:
|
||||||
|
cache:
|
||||||
|
condition: service_started
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.25
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
s3-tls:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
network_mode: service:s3
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/tls_bridge.py
|
||||||
|
- /bridge/s3-tls.json
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/s3:/tls:ro
|
||||||
|
- ./infra/tls:/bridge:ro
|
||||||
|
depends_on:
|
||||||
|
s3:
|
||||||
|
condition: service_started
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.25
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
otel-collector-tls-otlp:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
network_mode: service:otel-collector
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/tls_bridge.py
|
||||||
|
- /bridge/otel-collector-tls-otlp.json
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/otel-collector:/tls:ro
|
||||||
|
- ./infra/tls:/bridge:ro
|
||||||
|
depends_on:
|
||||||
|
otel-collector:
|
||||||
|
condition: service_started
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.25
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
otel-collector-tls-scrape:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
network_mode: service:otel-collector
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/tls_bridge.py
|
||||||
|
- /bridge/otel-collector-tls-scrape.json
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/otel-collector:/tls:ro
|
||||||
|
- ./infra/tls:/bridge:ro
|
||||||
|
depends_on:
|
||||||
|
otel-collector:
|
||||||
|
condition: service_started
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.25
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
prometheus-tls:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
network_mode: service:prometheus
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/tls_bridge.py
|
||||||
|
- /bridge/prometheus-tls.json
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/prometheus:/tls:ro
|
||||||
|
- ./infra/tls:/bridge:ro
|
||||||
|
depends_on:
|
||||||
|
prometheus:
|
||||||
|
condition: service_started
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.25
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
loki-tls:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
network_mode: service:loki
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/tls_bridge.py
|
||||||
|
- /bridge/loki-tls.json
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/loki:/tls:ro
|
||||||
|
- ./infra/tls:/bridge:ro
|
||||||
|
depends_on:
|
||||||
|
loki:
|
||||||
|
condition: service_started
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.25
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
tempo-tls-query:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
network_mode: service:tempo
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/tls_bridge.py
|
||||||
|
- /bridge/tempo-tls-query.json
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/tempo:/tls:ro
|
||||||
|
- ./infra/tls:/bridge:ro
|
||||||
|
depends_on:
|
||||||
|
tempo:
|
||||||
|
condition: service_started
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.25
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
tempo-tls-otlp:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
network_mode: service:tempo
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/tls_bridge.py
|
||||||
|
- /bridge/tempo-tls-otlp.json
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/tempo:/tls:ro
|
||||||
|
- ./infra/tls:/bridge:ro
|
||||||
|
depends_on:
|
||||||
|
tempo:
|
||||||
|
condition: service_started
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.25
|
||||||
|
read_only: true
|
||||||
|
security_opt: *id001
|
||||||
|
cap_drop: *id002
|
||||||
|
tmpfs: *id003
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
openbao:
|
||||||
|
image: openbao/openbao:2.3.1
|
||||||
|
command:
|
||||||
|
- server
|
||||||
|
- -config=/bao/config/openbao.hcl
|
||||||
|
volumes:
|
||||||
|
- ./infra/openbao.hcl:/bao/config/openbao.hcl:ro
|
||||||
|
- ./secrets/tls/openbao:/tls:ro
|
||||||
|
- baodata:/bao/data
|
||||||
|
ports:
|
||||||
|
- 127.0.0.1:18207:8200
|
||||||
|
mem_limit: 256m
|
||||||
|
cpus: 0.5
|
||||||
|
environment:
|
||||||
|
SKIP_SETCAP: 'true'
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
entrypoint:
|
||||||
|
- bao
|
||||||
|
user: 100:1000
|
||||||
|
depends_on:
|
||||||
|
bao-permissions:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
bao-permissions:
|
||||||
|
image: openbao/openbao:2.3.1
|
||||||
|
entrypoint:
|
||||||
|
- chown
|
||||||
|
command:
|
||||||
|
- 100:1000
|
||||||
|
- /bao/data
|
||||||
|
user: 0:0
|
||||||
|
volumes:
|
||||||
|
- baodata:/bao/data
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
cap_add:
|
||||||
|
- CHOWN
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 64m
|
||||||
|
cpus: 0.25
|
||||||
|
security-check:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
profiles:
|
||||||
|
- tools
|
||||||
|
entrypoint:
|
||||||
|
- python
|
||||||
|
command:
|
||||||
|
- /checks/check_security.py
|
||||||
|
volumes:
|
||||||
|
- ./student-tests:/checks:ro
|
||||||
|
- ./tests:/tests:ro
|
||||||
|
- ./secrets/tls/operator:/tls:ro
|
||||||
|
- ./secrets/tls:/identities:ro
|
||||||
|
- ./lab.json:/lab.json:ro
|
||||||
|
- ./contracts:/contracts:ro
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp:size=32m
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
mem_limit: 256m
|
||||||
|
cpus: 1.0
|
||||||
|
networks:
|
||||||
|
- default
|
||||||
|
- storage
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
maintenance:
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
profiles:
|
||||||
|
- tools
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- src/cleanup_attachments.py
|
||||||
|
env_file: .env
|
||||||
|
environment:
|
||||||
|
S3_ENDPOINT: https://s3:9002
|
||||||
|
DATABASE_URL_FILE: /run/secrets/database_url
|
||||||
|
CACHE_URL_FILE: /run/secrets/cache_url
|
||||||
|
CURSOR_KEY_FILE: /run/secrets/cursor_key
|
||||||
|
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access_key
|
||||||
|
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret_key
|
||||||
|
secrets:
|
||||||
|
- database_url
|
||||||
|
- cache_url
|
||||||
|
- cursor_key
|
||||||
|
- s3_admin_access_key
|
||||||
|
- s3_admin_secret_key
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/operator:/tls:ro
|
||||||
|
networks:
|
||||||
|
- default
|
||||||
|
- storage
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp:size=32m
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
mem_limit: 256m
|
||||||
|
cpus: 0.5
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
secrets:
|
||||||
|
broker_url:
|
||||||
|
file: ./secrets/broker_url
|
||||||
|
db_password:
|
||||||
|
file: ./secrets/db_password
|
||||||
|
database_url:
|
||||||
|
file: ./secrets/database_url
|
||||||
|
cache_url:
|
||||||
|
file: ./secrets/cache_url
|
||||||
|
cursor_key:
|
||||||
|
file: ./secrets/cursor_key
|
||||||
|
s3_config:
|
||||||
|
file: ./secrets/s3_config
|
||||||
|
s3_admin_access_key:
|
||||||
|
file: ./secrets/s3_admin_access_key
|
||||||
|
s3_admin_secret_key:
|
||||||
|
file: ./secrets/s3_admin_secret_key
|
||||||
|
s3_access_key_id:
|
||||||
|
file: ./secrets/s3_access_key_id
|
||||||
|
s3_secret_access_key:
|
||||||
|
file: ./secrets/s3_secret_access_key
|
||||||
|
volumes:
|
||||||
|
pgdata: null
|
||||||
|
objects: null
|
||||||
|
brokerdata: null
|
||||||
|
metricsdata: null
|
||||||
|
logsdata: null
|
||||||
|
tracesdata: null
|
||||||
|
grafanadata: null
|
||||||
|
baodata: {}
|
||||||
|
networks:
|
||||||
|
default: {}
|
||||||
|
storage:
|
||||||
|
internal: true
|
||||||
+49
-27
@@ -1,37 +1,59 @@
|
|||||||
# Матрица доверия — заполнить в решении lab7
|
# Матрица доверия
|
||||||
|
|
||||||
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
Все TLS-сертификаты выдаёт локальный лабораторный CA. Leaf действуют 24 часа.
|
||||||
|
Серверы проверяются по CA и DNS SAN. Приватный ключ CA и operator init/unseal
|
||||||
|
остаются в secrets/operator на машине оператора и не монтируются в приложения.
|
||||||
|
|
||||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
| Связь | Порт и протокол | Идентичность и разрешения | Проверка |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
| Клиент → LB | 8443 HTTPS, localhost:18443 | SAN lb/localhost, Bearer, общий login limit | public smoke/security, check_security.py |
|
||||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
| LB → обе API | 8443 mTLS | SAN lb; operator имеет только GET для диагностики | без cert, другой CA, SAN foreign отклоняются |
|
||||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
| API/worker → PostgreSQL | 5432 native TLS verify-full | Разные пароли и роли api/worker/dispatcher, plaintext запрещён pg_hba | pg_stat_ssl, plaintext denied, worker DELETE users denied |
|
||||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
| API/worker → S3 | 9002 mTLS | SAN api-a/api-b/worker; отдельные S3 access keys; API PUT ограничен staging/UUID | check_security.py, final-prefix write denied |
|
||||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
| Dispatcher/worker → broker | 6380 mTLS | SAN dispatcher/worker плюс Redis ACL producer/consumer только images | ping allowed, противоположная операция denied |
|
||||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
| API/worker → Collector | 4319 mTLS | SAN api-a/api-b/worker/dispatcher, только POST | foreign, без cert, другой CA denied |
|
||||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
| Collector → Loki/Tempo | 3101/4319 mTLS | SAN otel-collector, только POST | TLS exports, реальные данные в backend |
|
||||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
| Prometheus → Collector scrape | 8890 mTLS | SAN prometheus, только GET | реальная http_requests_total |
|
||||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
| Grafana → источники | 9091/3101/3201 mTLS | SAN grafana, только GET | provisioning, endpoint health |
|
||||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
| API/worker → OpenBao | 8200 HTTPS + cert auth | SAN роли, policy secret/data/свой-сервис, token TTL 60 с/max 120 с | own read allowed, other path/policy denied |
|
||||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
| Оператор → OpenBao/Grafana | 8200/3000 HTTPS, только loopback хоста | operator root credential для init/unseal; Grafana admin с локальным случайным паролем | сертификат проверяется, пароль вне Git |
|
||||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
| API → Redis profiles | 6380 mTLS + ACL | SAN API, команда get/setex для user:v1:* | TLS используется ProfileCache, ACL ограничивает ключи |
|
||||||
|
| Внутренние каналы SeaweedFS | loopback одного namespace | Native master/filer/volume и HTTP backend привязаны 127.0.0.1 | опубликован только S3 TLS proxy в закрытой storage-сети |
|
||||||
|
| Другие plaintext hops | loopback одного namespace | API, Redis, Collector и backend находятся за TLS bridge; native порт недоступен через bridge network | проверка api:8080 denied, конфиги bind |
|
||||||
|
| Replication между узлами | N/A | Одноузловые stateful компоненты | отказ узла не заявлен |
|
||||||
|
|
||||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
TLS bridge ограничивает SAN и проверяет список отозванных serial при каждом новом
|
||||||
|
соединении. HTTP roles ограничены методами, соединение закрывается после запроса.
|
||||||
|
Для S3 PUT API разрешены только UUID-ключи staging. Native S3 credentials дополнительно
|
||||||
|
ограничены bucket. Operator GET на диагностических proxy не даёт права ingest.
|
||||||
|
|
||||||
## Обязательные отрицательные проверки
|
## Bootstrap и ротация
|
||||||
|
|
||||||
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
|
Оператор запускает scripts/start.py. OpenBao работает в server mode с file storage.
|
||||||
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех.
|
Root token и единственная unseal share сохраняются только в operator-файле.
|
||||||
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity.
|
Это ручной учебный bootstrap, оператор владеет файлом и запускает init/unseal явно.
|
||||||
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
|
Контейнер OpenBao не получает этот файл. Сервисы используют свои leaf certificates
|
||||||
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
|
для auth/cert, читают только свой KV path и получают короткоживущий token.
|
||||||
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
|
Повторная аутентификация выполняется при очередном чтении после истечения cache TTL
|
||||||
|
не более 15 с. Рабочие DB/S3 credentials сохраняются в клиентских пулах до рестарта
|
||||||
|
сервиса. Ротация выполняется scripts/rotate.py с переподключением клиентов.
|
||||||
|
|
||||||
## Bootstrap и эксплуатация
|
rotate.py secret меняет пароль api в PostgreSQL и KV, перезапускает API и TLS bridge.
|
||||||
|
rotate.py certificate выдаёт новый leaf api-a, публикует CRL в OpenBao и отозванные
|
||||||
|
serial в proxy. Все проверки отзыва выполняют новое соединение.
|
||||||
|
Новый образ при ротации не создаётся. CA и лист отзыва являются operator trust anchor.
|
||||||
|
Доступ к их изменению равноценен администрированию стенда.
|
||||||
|
|
||||||
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
|
## Hardening
|
||||||
|
|
||||||
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 — хорошее расширение, но не обязательное название технологии.
|
API, worker, dispatcher и TLS bridges работают UID 10001, read_only,
|
||||||
|
no-new-privileges, drop ALL capabilities, с CPU/RAM-лимитами и tmpfs.
|
||||||
|
PostgreSQL, SeaweedFS, Redis и хранилища telemetry имеют writable именованные тома.
|
||||||
|
Одноразовый bao-permissions работает root только с CHOWN для владельца нового тома.
|
||||||
|
OpenBao затем работает UID 100 с drop ALL capabilities и disable_mlock.
|
||||||
|
Docker socket, host networking и privileged отсутствуют.
|
||||||
|
|
||||||
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
|
На Linux каталог secrets закрыт mode 0700. Leaf keys внутри отдельных TLS-каталогов
|
||||||
|
читаются разными UID образов через read-only bind mount. Каждый обычный контейнер
|
||||||
|
получает только свой TLS-каталог. CA key и init/unseal файл имеют mode 0600
|
||||||
|
и остаются вне контейнеров приложений.
|
||||||
|
|||||||
+16
-3
@@ -1,5 +1,18 @@
|
|||||||
# Доказательства
|
# Результаты проверок
|
||||||
|
|
||||||
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
|
Дата: 30.11.2026. Локальный Docker Desktop, лимиты CPU/RAM заданы в compose.yaml.
|
||||||
|
|
||||||
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
|
На Windows GNU make отсутствует; выполнены Python-команды из соответствующих targets Makefile.
|
||||||
|
Проверки относятся к локальному стенду; удалённый CI не запускался.
|
||||||
|
|
||||||
|
- smoke.txt и public-security.txt — публичные HTTPS проверки.
|
||||||
|
- contracts.txt — structure и полный OpenAPI (make check, make validate).
|
||||||
|
- clean-start.txt — bootstrap отдельного Compose project с новыми томами, CA и secrets.
|
||||||
|
- clean-security.txt — отрицательные проверки на этом чистом стенде.
|
||||||
|
- grafana-tls.txt — запросы Grafana к Prometheus, Loki и Tempo через mTLS.
|
||||||
|
- rotation.txt — ротация, отзыв, expiry и seal/unseal.
|
||||||
|
- persistence.txt и failover.txt — сохранность и отказ реплики через HTTPS.
|
||||||
|
- password-benchmark.json — параметры, время и RSS Argon2id.
|
||||||
|
- dependency-audit.json — scan установленных Python-пакетов.
|
||||||
|
|
||||||
|
Повторная сборка после фиксации транзитивных версий прервалась по сетевому timeout files.pythonhosted.org (final-start.txt). Фиксированные версии сняты с уже проверенного образа; последующие функциональные проверки выполнены на нём.
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
Container lab7-clean-775b3466-security-check-run-dcb8fd846fd6 Creating
|
||||||
|
Container lab7-clean-775b3466-security-check-run-dcb8fd846fd6 Created
|
||||||
|
PASS: HTTPS API, asynchronous images and cross-user ACL
|
||||||
|
PASS: server CA and hostname verification
|
||||||
|
PASS: both API replicas require allowed LB certificate; plaintext bypass closed
|
||||||
|
PASS: broker mTLS identity and separate producer/consumer ACL
|
||||||
|
PASS: Collector requires allowed service identities
|
||||||
|
PASS: OpenBao scoped read, cross-service and policy access denied, token TTL bounded
|
||||||
|
PASS: PostgreSQL TLS, Argon2id and least-privilege worker role
|
||||||
|
PASS: successful login upgrades legacy scrypt hash to Argon2id
|
||||||
|
PASS: API S3 identity cannot write final-object prefix
|
||||||
|
PASS: shared login limit across both replicas with 429/Retry-After
|
||||||
|
PASS: TLS telemetry query succeeds and logs exclude test password/session token
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
Image mtusi-messenger:lab7 Building
|
||||||
|
#1 [internal] load local bake definitions
|
||||||
|
#1 reading from stdin 624B 0.1s done
|
||||||
|
#1 DONE 0.1s
|
||||||
|
|
||||||
|
#2 [internal] load build definition from Dockerfile
|
||||||
|
#2 transferring dockerfile: 663B done
|
||||||
|
#2 DONE 0.0s
|
||||||
|
|
||||||
|
#3 [internal] load metadata for docker.io/library/python:3.13.5-slim-bookworm@sha256:4c2cf9917bd1cbacc5e9b07320025bdb7cdf2df7b0ceaccb55e9dd7e30987419
|
||||||
|
#3 DONE 0.0s
|
||||||
|
|
||||||
|
#4 [internal] load .dockerignore
|
||||||
|
#4 transferring context: 212B done
|
||||||
|
#4 DONE 0.0s
|
||||||
|
|
||||||
|
#5 [internal] load build context
|
||||||
|
#5 transferring context: 71.08kB 0.0s done
|
||||||
|
#5 DONE 0.1s
|
||||||
|
|
||||||
|
#6 [1/6] FROM docker.io/library/python:3.13.5-slim-bookworm@sha256:4c2cf9917bd1cbacc5e9b07320025bdb7cdf2df7b0ceaccb55e9dd7e30987419
|
||||||
|
#6 resolve docker.io/library/python:3.13.5-slim-bookworm@sha256:4c2cf9917bd1cbacc5e9b07320025bdb7cdf2df7b0ceaccb55e9dd7e30987419 0.0s done
|
||||||
|
#6 DONE 0.0s
|
||||||
|
|
||||||
|
#7 [2/6] WORKDIR /app
|
||||||
|
#7 CACHED
|
||||||
|
|
||||||
|
#8 [5/6] COPY migrations/ ./migrations/
|
||||||
|
#8 CACHED
|
||||||
|
|
||||||
|
#9 [3/6] COPY requirements.txt .
|
||||||
|
#9 CACHED
|
||||||
|
|
||||||
|
#10 [4/6] RUN pip install --no-cache-dir pip==26.2 && pip install --no-cache-dir -r requirements.txt
|
||||||
|
#10 CACHED
|
||||||
|
|
||||||
|
#11 [6/6] COPY src/ ./src/
|
||||||
|
#11 CACHED
|
||||||
|
|
||||||
|
#12 exporting to image
|
||||||
|
#12 exporting layers done
|
||||||
|
#12 exporting manifest sha256:119d7926b4d98798df36e385e622d262fe582a03121264d65f652e12fece0453 0.0s done
|
||||||
|
#12 exporting config sha256:47f47a432996deb4312e59afb3e7a717d0ae415c028470da991d4408de558093 0.0s done
|
||||||
|
#12 exporting attestation manifest sha256:22a29e30b6c7aa57c168b50b894ad84a653c89a059e999bda9950ba91b93b11f 0.0s done
|
||||||
|
#12 exporting manifest list sha256:0b3c8b6988dae488bc371213e1ad97e0c8a0b9d68553fe9d3c3f379adf8091d0
|
||||||
|
#12 exporting manifest list sha256:0b3c8b6988dae488bc371213e1ad97e0c8a0b9d68553fe9d3c3f379adf8091d0 0.0s done
|
||||||
|
#12 naming to docker.io/library/mtusi-messenger:lab7 done
|
||||||
|
#12 unpacking to docker.io/library/mtusi-messenger:lab7 0.0s done
|
||||||
|
#12 DONE 0.1s
|
||||||
|
|
||||||
|
#13 resolving provenance for metadata file
|
||||||
|
#13 DONE 0.0s
|
||||||
|
Image mtusi-messenger:lab7 Built
|
||||||
|
Network lab7-clean-775b3466_storage Creating
|
||||||
|
Network lab7-clean-775b3466_storage Created
|
||||||
|
Network lab7-clean-775b3466_default Creating
|
||||||
|
Network lab7-clean-775b3466_default Created
|
||||||
|
Volume lab7-clean-775b3466_baodata Creating
|
||||||
|
Volume lab7-clean-775b3466_baodata Created
|
||||||
|
Volume lab7-clean-775b3466_pgdata Creating
|
||||||
|
Volume lab7-clean-775b3466_pgdata Created
|
||||||
|
Volume lab7-clean-775b3466_objects Creating
|
||||||
|
Volume lab7-clean-775b3466_objects Created
|
||||||
|
Volume lab7-clean-775b3466_brokerdata Creating
|
||||||
|
Volume lab7-clean-775b3466_brokerdata Created
|
||||||
|
Container lab7-clean-775b3466-s3-1 Creating
|
||||||
|
Container lab7-clean-775b3466-broker-1 Creating
|
||||||
|
Container lab7-clean-775b3466-cache-1 Creating
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Creating
|
||||||
|
Container lab7-clean-775b3466-db-1 Creating
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Created
|
||||||
|
Container lab7-clean-775b3466-openbao-1 Creating
|
||||||
|
Container lab7-clean-775b3466-s3-1 Created
|
||||||
|
Container lab7-clean-775b3466-s3-tls-1 Creating
|
||||||
|
Container lab7-clean-775b3466-broker-1 Created
|
||||||
|
Container lab7-clean-775b3466-broker-tls-1 Creating
|
||||||
|
Container lab7-clean-775b3466-cache-1 Created
|
||||||
|
Container lab7-clean-775b3466-cache-tls-1 Creating
|
||||||
|
Container lab7-clean-775b3466-db-1 Created
|
||||||
|
Container lab7-clean-775b3466-openbao-1 Created
|
||||||
|
Container lab7-clean-775b3466-broker-tls-1 Created
|
||||||
|
Container lab7-clean-775b3466-s3-tls-1 Created
|
||||||
|
Container lab7-clean-775b3466-cache-tls-1 Created
|
||||||
|
Container lab7-clean-775b3466-s3-1 Starting
|
||||||
|
Container lab7-clean-775b3466-cache-1 Starting
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Starting
|
||||||
|
Container lab7-clean-775b3466-db-1 Starting
|
||||||
|
Container lab7-clean-775b3466-broker-1 Starting
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Started
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-s3-1 Started
|
||||||
|
Container lab7-clean-775b3466-s3-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-broker-1 Started
|
||||||
|
Container lab7-clean-775b3466-broker-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-cache-1 Started
|
||||||
|
Container lab7-clean-775b3466-cache-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-db-1 Started
|
||||||
|
Container lab7-clean-775b3466-broker-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-s3-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-cache-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Exited
|
||||||
|
Container lab7-clean-775b3466-openbao-1 Starting
|
||||||
|
Container lab7-clean-775b3466-openbao-1 Started
|
||||||
|
Container lab7-clean-775b3466-broker-tls-1 Recreate
|
||||||
|
Container lab7-clean-775b3466-cache-tls-1 Recreate
|
||||||
|
Container lab7-clean-775b3466-s3-tls-1 Recreate
|
||||||
|
Container lab7-clean-775b3466-cache-tls-1 Recreated
|
||||||
|
Container lab7-clean-775b3466-broker-tls-1 Recreated
|
||||||
|
Container lab7-clean-775b3466-s3-tls-1 Recreated
|
||||||
|
Container lab7-clean-775b3466-s3-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-broker-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-cache-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-cache-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-s3-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-broker-tls-1 Started
|
||||||
|
OpenBao initialized, unsealed and scoped policies configured
|
||||||
|
Container lab7-clean-775b3466-db-1 Running
|
||||||
|
Container lab7-clean-775b3466-db-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-db-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-migrate-run-91b99c8cf269 Creating
|
||||||
|
Container lab7-clean-775b3466-migrate-run-91b99c8cf269 Created
|
||||||
|
Applied 001_initial.sql
|
||||||
|
Applied 002_idempotency.sql
|
||||||
|
Applied 003_attachments.sql
|
||||||
|
Applied 004_jobs.sql
|
||||||
|
Applied 005_trace_context.sql
|
||||||
|
Applied 006_login_limits.sql
|
||||||
|
Scoped database roles configured
|
||||||
|
Volume lab7-clean-775b3466_logsdata Creating
|
||||||
|
Volume lab7-clean-775b3466_logsdata Created
|
||||||
|
Volume lab7-clean-775b3466_tracesdata Creating
|
||||||
|
Volume lab7-clean-775b3466_tracesdata Created
|
||||||
|
Volume lab7-clean-775b3466_grafanadata Creating
|
||||||
|
Volume lab7-clean-775b3466_grafanadata Created
|
||||||
|
Volume lab7-clean-775b3466_metricsdata Creating
|
||||||
|
Volume lab7-clean-775b3466_metricsdata Created
|
||||||
|
Container lab7-clean-775b3466-prometheus-1 Creating
|
||||||
|
Container lab7-clean-775b3466-s3-1 Running
|
||||||
|
Container lab7-clean-775b3466-cache-1 Running
|
||||||
|
Container lab7-clean-775b3466-tempo-1 Creating
|
||||||
|
Container lab7-clean-775b3466-s3-tls-1 Running
|
||||||
|
Container lab7-clean-775b3466-loki-1 Creating
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Creating
|
||||||
|
Container lab7-clean-775b3466-broker-1 Running
|
||||||
|
Container lab7-clean-775b3466-grafana-1 Creating
|
||||||
|
Container lab7-clean-775b3466-otel-collector-1 Creating
|
||||||
|
Container lab7-clean-775b3466-cache-tls-1 Running
|
||||||
|
Container lab7-clean-775b3466-openbao-1 Running
|
||||||
|
Container lab7-clean-775b3466-broker-tls-1 Running
|
||||||
|
Container lab7-clean-775b3466-db-1 Running
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Creating
|
||||||
|
Container lab7-clean-775b3466-otel-collector-1 Created
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-otlp-1 Creating
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-scrape-1 Creating
|
||||||
|
Container lab7-clean-775b3466-prometheus-1 Created
|
||||||
|
Container lab7-clean-775b3466-prometheus-tls-1 Creating
|
||||||
|
Container lab7-clean-775b3466-grafana-1 Created
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Created
|
||||||
|
Container lab7-clean-775b3466-tempo-1 Created
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-query-1 Creating
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-otlp-1 Creating
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Created
|
||||||
|
Container lab7-clean-775b3466-worker-1 Creating
|
||||||
|
Container lab7-clean-775b3466-dispatcher-1 Creating
|
||||||
|
Container lab7-clean-775b3466-loki-1 Created
|
||||||
|
Container lab7-clean-775b3466-loki-tls-1 Creating
|
||||||
|
Container lab7-clean-775b3466-api-b-1 Creating
|
||||||
|
Container lab7-clean-775b3466-api-a-1 Creating
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-otlp-1 Created
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-scrape-1 Created
|
||||||
|
Container lab7-clean-775b3466-prometheus-tls-1 Created
|
||||||
|
Container lab7-clean-775b3466-worker-1 Created
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-query-1 Created
|
||||||
|
Container lab7-clean-775b3466-dispatcher-1 Created
|
||||||
|
Container lab7-clean-775b3466-api-b-1 Created
|
||||||
|
Container lab7-clean-775b3466-api-b-tls-1 Creating
|
||||||
|
Container lab7-clean-775b3466-loki-tls-1 Created
|
||||||
|
Container lab7-clean-775b3466-api-a-1 Created
|
||||||
|
Container lab7-clean-775b3466-api-a-tls-1 Creating
|
||||||
|
Container lab7-clean-775b3466-lb-1 Creating
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-otlp-1 Created
|
||||||
|
Container lab7-clean-775b3466-api-b-tls-1 Created
|
||||||
|
Container lab7-clean-775b3466-api-a-tls-1 Created
|
||||||
|
Container lab7-clean-775b3466-lb-1 Created
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Starting
|
||||||
|
Container lab7-clean-775b3466-grafana-1 Starting
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Starting
|
||||||
|
Container lab7-clean-775b3466-prometheus-1 Starting
|
||||||
|
Container lab7-clean-775b3466-otel-collector-1 Starting
|
||||||
|
Container lab7-clean-775b3466-loki-1 Starting
|
||||||
|
Container lab7-clean-775b3466-tempo-1 Starting
|
||||||
|
Container lab7-clean-775b3466-db-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-db-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Starting
|
||||||
|
Container lab7-clean-775b3466-tempo-1 Started
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-query-1 Starting
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-otlp-1 Starting
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Started
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-loki-1 Started
|
||||||
|
Container lab7-clean-775b3466-loki-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-prometheus-1 Started
|
||||||
|
Container lab7-clean-775b3466-prometheus-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-otel-collector-1 Started
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-scrape-1 Starting
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-otlp-1 Starting
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-query-1 Started
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-otlp-1 Started
|
||||||
|
Container lab7-clean-775b3466-grafana-1 Started
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Started
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Started
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-scrape-1 Started
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Exited
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-otlp-1 Started
|
||||||
|
Container lab7-clean-775b3466-loki-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-prometheus-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Exited
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Exited
|
||||||
|
Container lab7-clean-775b3466-dispatcher-1 Starting
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Exited
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Exited
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Exited
|
||||||
|
Container lab7-clean-775b3466-api-b-1 Starting
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Exited
|
||||||
|
Container lab7-clean-775b3466-api-a-1 Starting
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Exited
|
||||||
|
Container lab7-clean-775b3466-worker-1 Starting
|
||||||
|
Container lab7-clean-775b3466-dispatcher-1 Started
|
||||||
|
Container lab7-clean-775b3466-api-a-1 Started
|
||||||
|
Container lab7-clean-775b3466-api-a-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-api-b-1 Started
|
||||||
|
Container lab7-clean-775b3466-api-b-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-api-a-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-api-b-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-worker-1 Started
|
||||||
|
Container lab7-clean-775b3466-api-a-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-api-b-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-api-a-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-api-b-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-lb-1 Starting
|
||||||
|
Container lab7-clean-775b3466-lb-1 Started
|
||||||
|
Container lab7-clean-775b3466-prometheus-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-grafana-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-broker-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-tempo-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-cache-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-api-b-tls-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-query-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-dispatcher-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-s3-tls-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-s3-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-otel-collector-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-otlp-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-cache-tls-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-api-b-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-broker-tls-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-loki-tls-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-otlp-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-lb-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-openbao-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-db-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-scrape-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-api-a-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-loki-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-prometheus-tls-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-worker-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-api-a-tls-1 Waiting
|
||||||
|
Container lab7-clean-775b3466-s3-tls-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-dispatcher-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-tempo-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-loki-tls-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-api-b-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-cache-tls-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-bao-permissions-1 Exited
|
||||||
|
Container lab7-clean-775b3466-loki-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-api-b-tls-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-otlp-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-cache-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-grafana-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-otel-collector-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-migrate-1 Exited
|
||||||
|
Container lab7-clean-775b3466-s3-init-1 Exited
|
||||||
|
Container lab7-clean-775b3466-prometheus-tls-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-prometheus-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-broker-tls-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-openbao-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-scrape-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-broker-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-query-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-otlp-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-api-a-tls-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-s3-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-lb-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-worker-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-api-a-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-db-1 Healthy
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-otlp-1 Recreate
|
||||||
|
Container lab7-clean-775b3466-loki-tls-1 Recreate
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-scrape-1 Recreate
|
||||||
|
Container lab7-clean-775b3466-api-b-tls-1 Recreate
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-otlp-1 Recreate
|
||||||
|
Container lab7-clean-775b3466-prometheus-tls-1 Recreate
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-query-1 Recreate
|
||||||
|
Container lab7-clean-775b3466-api-a-tls-1 Recreate
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-otlp-1 Recreated
|
||||||
|
Container lab7-clean-775b3466-api-a-tls-1 Recreated
|
||||||
|
Container lab7-clean-775b3466-prometheus-tls-1 Recreated
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-otlp-1 Recreated
|
||||||
|
Container lab7-clean-775b3466-loki-tls-1 Recreated
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-query-1 Recreated
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-scrape-1 Recreated
|
||||||
|
Container lab7-clean-775b3466-api-b-tls-1 Recreated
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-scrape-1 Starting
|
||||||
|
Container lab7-clean-775b3466-api-a-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-loki-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-query-1 Starting
|
||||||
|
Container lab7-clean-775b3466-prometheus-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-api-b-tls-1 Starting
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-otlp-1 Starting
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-otlp-1 Starting
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-query-1 Started
|
||||||
|
Container lab7-clean-775b3466-api-b-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-tempo-tls-otlp-1 Started
|
||||||
|
Container lab7-clean-775b3466-prometheus-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-api-a-tls-1 Started
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-otlp-1 Started
|
||||||
|
Container lab7-clean-775b3466-otel-collector-tls-scrape-1 Started
|
||||||
|
Container lab7-clean-775b3466-loki-tls-1 Started
|
||||||
|
HTTPS stack is ready
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
|
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
|||||||
|
{"dependencies": [{"name": "argon2-cffi", "version": "25.1.0", "vulns": []}, {"name": "argon2-cffi-bindings", "version": "26.2.0", "vulns": []}, {"name": "boto3", "version": "1.39.3", "vulns": []}, {"name": "botocore", "version": "1.39.3", "vulns": []}, {"name": "certifi", "version": "2026.11.20", "vulns": []}, {"name": "cffi", "version": "2.1.1", "vulns": []}, {"name": "charset-normalizer", "version": "3.5.3", "vulns": []}, {"name": "cryptography", "version": "50.0.0", "vulns": []}, {"name": "googleapis-common-protos", "version": "1.76.0", "vulns": []}, {"name": "idna", "version": "3.20", "vulns": []}, {"name": "jmespath", "version": "1.0.1", "vulns": []}, {"name": "opentelemetry-api", "version": "1.45.2", "vulns": []}, {"name": "opentelemetry-exporter-http-transport", "version": "0.66b2", "vulns": []}, {"name": "opentelemetry-exporter-otlp-common", "version": "0.66b2", "vulns": []}, {"name": "opentelemetry-exporter-otlp-proto-common", "version": "1.45.2", "vulns": []}, {"name": "opentelemetry-exporter-otlp-proto-http", "version": "1.45.2", "vulns": []}, {"name": "opentelemetry-proto", "version": "1.45.2", "vulns": []}, {"name": "opentelemetry-sdk", "version": "1.45.2", "vulns": []}, {"name": "opentelemetry-semantic-conventions", "version": "0.66b2", "vulns": []}, {"name": "pillow", "version": "13.0.0", "vulns": []}, {"name": "pip", "version": "26.2", "vulns": []}, {"name": "protobuf", "version": "7.36.2", "vulns": []}, {"name": "psycopg", "version": "3.2.9", "vulns": []}, {"name": "psycopg-binary", "version": "3.2.9", "vulns": []}, {"name": "psycopg-pool", "version": "3.2.6", "vulns": []}, {"name": "pycparser", "version": "3.12", "vulns": []}, {"name": "python-dateutil", "version": "2.9.0.post0", "vulns": []}, {"name": "redis", "version": "6.2.0", "vulns": []}, {"name": "requests", "version": "2.34.2", "vulns": []}, {"name": "s3transfer", "version": "0.13.0", "vulns": []}, {"name": "six", "version": "1.17.0", "vulns": []}, {"name": "typing-extensions", "version": "4.14.0", "vulns": []}, {"name": "urllib3", "version": "2.8.0", "vulns": []}], "fixes": []}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
{"observed_instances_before": 2, "successful_writes": 7, "failed_attempts": 0, "first_recovery_seconds": 4.19}
|
||||||
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
Image mtusi-messenger:lab7 Building
|
||||||
|
#1 [internal] load local bake definitions
|
||||||
|
#1 reading from stdin 554B 0.1s done
|
||||||
|
#1 DONE 0.1s
|
||||||
|
|
||||||
|
#2 [internal] load build definition from Dockerfile
|
||||||
|
#2 transferring dockerfile: 663B done
|
||||||
|
#2 DONE 0.0s
|
||||||
|
|
||||||
|
#3 [internal] load metadata for docker.io/library/python:3.13.5-slim-bookworm@sha256:4c2cf9917bd1cbacc5e9b07320025bdb7cdf2df7b0ceaccb55e9dd7e30987419
|
||||||
|
#3 DONE 20.9s
|
||||||
|
|
||||||
|
#4 [internal] load .dockerignore
|
||||||
|
#4 transferring context: 212B done
|
||||||
|
#4 DONE 0.0s
|
||||||
|
|
||||||
|
#5 [internal] load build context
|
||||||
|
#5 transferring context: 1.71kB done
|
||||||
|
#5 DONE 0.0s
|
||||||
|
|
||||||
|
#6 [1/6] FROM docker.io/library/python:3.13.5-slim-bookworm@sha256:4c2cf9917bd1cbacc5e9b07320025bdb7cdf2df7b0ceaccb55e9dd7e30987419
|
||||||
|
#6 resolve docker.io/library/python:3.13.5-slim-bookworm@sha256:4c2cf9917bd1cbacc5e9b07320025bdb7cdf2df7b0ceaccb55e9dd7e30987419
|
||||||
|
#6 resolve docker.io/library/python:3.13.5-slim-bookworm@sha256:4c2cf9917bd1cbacc5e9b07320025bdb7cdf2df7b0ceaccb55e9dd7e30987419 20.1s done
|
||||||
|
#6 DONE 20.1s
|
||||||
|
|
||||||
|
#7 [2/6] WORKDIR /app
|
||||||
|
#7 CACHED
|
||||||
|
|
||||||
|
#8 [3/6] COPY requirements.txt .
|
||||||
|
#8 DONE 0.0s
|
||||||
|
|
||||||
|
#9 [4/6] RUN pip install --no-cache-dir pip==26.2 && pip install --no-cache-dir -r requirements.txt
|
||||||
|
#9 1.598 Collecting pip==26.2
|
||||||
|
#9 16.72 WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata
|
||||||
|
#9 32.27 WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata
|
||||||
|
#9 48.32 WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata
|
||||||
|
#9 65.37 WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata
|
||||||
|
#9 84.49 WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata
|
||||||
|
#9 99.55 ERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata (Caused by ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)"))
|
||||||
|
#9 99.55
|
||||||
|
#9 99.75
|
||||||
|
#9 99.75 [notice] A new release of pip is available: 25.1.1 -> 26.3
|
||||||
|
#9 99.75 [notice] To update, run: pip install --upgrade pip
|
||||||
|
#9 ERROR: process "/bin/sh -c pip install --no-cache-dir pip==26.2 && pip install --no-cache-dir -r requirements.txt" did not complete successfully: exit code: 1
|
||||||
|
------
|
||||||
|
> [4/6] RUN pip install --no-cache-dir pip==26.2 && pip install --no-cache-dir -r requirements.txt:
|
||||||
|
16.72 WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata
|
||||||
|
32.27 WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata
|
||||||
|
48.32 WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata
|
||||||
|
65.37 WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata
|
||||||
|
84.49 WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata
|
||||||
|
99.55 ERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/62/36/a3aed958d60531cb442b7ab4596cda7b3621cfb916f8ae1d6769795c7dc1/pip-26.2-py3-none-any.whl.metadata (Caused by ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)"))
|
||||||
|
99.55
|
||||||
|
99.75
|
||||||
|
99.75 [notice] A new release of pip is available: 25.1.1 -> 26.3
|
||||||
|
99.75 [notice] To update, run: pip install --upgrade pip
|
||||||
|
------
|
||||||
|
Dockerfile:6
|
||||||
|
|
||||||
|
--------------------
|
||||||
|
|
||||||
|
4 | WORKDIR /app
|
||||||
|
|
||||||
|
5 | COPY requirements.txt .
|
||||||
|
|
||||||
|
6 | >>> RUN pip install --no-cache-dir pip==26.2 && pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
7 | COPY migrations/ ./migrations/
|
||||||
|
|
||||||
|
8 | COPY src/ ./src/
|
||||||
|
|
||||||
|
--------------------
|
||||||
|
|
||||||
|
failed to solve: process "/bin/sh -c pip install --no-cache-dir pip==26.2 && pip install --no-cache-dir -r requirements.txt" did not complete successfully: exit code: 1
|
||||||
|
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "C:\Users\User\Desktop\vp\mtusi2026lab7\scripts\start.py", line 19, in <module>
|
||||||
|
run("docker", "compose", "build", "migrate")
|
||||||
|
~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
File "C:\Users\User\Desktop\vp\mtusi2026lab7\scripts\start.py", line 13, in run
|
||||||
|
subprocess.run(args, cwd=ROOT, check=True, timeout=300)
|
||||||
|
~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
File "C:\Users\User\AppData\Local\Programs\Python\Python313\Lib\subprocess.py", line 577, in run
|
||||||
|
raise CalledProcessError(retcode, process.args,
|
||||||
|
output=stdout, stderr=stderr)
|
||||||
|
subprocess.CalledProcessError: Command '('docker', 'compose', 'build', 'migrate')' returned non-zero exit status 1.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
PASS: Grafana queries Prometheus through verified mTLS
|
||||||
|
PASS: Grafana queries Loki through verified mTLS
|
||||||
|
PASS: Grafana queries Tempo through verified mTLS
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"samples": 20, "operation": "hash_plus_verify", "memory_kib": 19456, "time_cost": 2, "parallelism": 1, "p50_seconds": 0.0423, "p95_seconds": 0.0674, "peak_rss_bytes": 40701952, "server_max_parallel_hashes": 2}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
Container mtusi2026lab7-api-a-1 Restarting
|
||||||
|
Container mtusi2026lab7-api-b-1 Restarting
|
||||||
|
Container mtusi2026lab7-api-a-1 Started
|
||||||
|
Container mtusi2026lab7-api-b-1 Started
|
||||||
|
Container mtusi2026lab7-api-b-tls-1 Restarting
|
||||||
|
Container mtusi2026lab7-api-a-tls-1 Restarting
|
||||||
|
Container mtusi2026lab7-api-a-tls-1 Started
|
||||||
|
Container mtusi2026lab7-api-b-tls-1 Started
|
||||||
|
Rotated API database credential without rebuilding images
|
||||||
|
PASS: old DB credential rejected on new connection
|
||||||
|
Container mtusi2026lab7-api-a-1 Restarting
|
||||||
|
Container mtusi2026lab7-api-a-tls-1 Restarting
|
||||||
|
Container mtusi2026lab7-api-a-1 Started
|
||||||
|
Container mtusi2026lab7-api-a-tls-1 Started
|
||||||
|
Rotated API leaf certificate and revoked previous identity
|
||||||
|
PASS: revoked leaf rejected by Collector and OpenBao
|
||||||
|
PASS: expired OpenBao service token rejected
|
||||||
|
OpenBao initialized, unsealed and scoped policies configured
|
||||||
|
PASS: sealed OpenBao refuses service authentication
|
||||||
|
OpenBao initialized, unsealed and scoped policies configured
|
||||||
|
PASS: original session valid after credential/certificate rotation and unseal
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
Container mtusi2026lab7-security-check-run-b6cd245d3893 Creating
|
||||||
|
Container mtusi2026lab7-security-check-run-b6cd245d3893 Created
|
||||||
|
PASS: HTTPS API, asynchronous images and cross-user ACL
|
||||||
|
PASS: server CA and hostname verification
|
||||||
|
PASS: both API replicas require allowed LB certificate; plaintext bypass closed
|
||||||
|
PASS: broker mTLS identity and separate producer/consumer ACL
|
||||||
|
PASS: Collector requires allowed service identities
|
||||||
|
PASS: OpenBao scoped read, cross-service and policy access denied, token TTL bounded
|
||||||
|
PASS: PostgreSQL TLS, Argon2id and least-privilege worker role
|
||||||
|
PASS: successful login upgrades legacy scrypt hash to Argon2id
|
||||||
|
PASS: API S3 identity cannot write final-object prefix
|
||||||
|
PASS: shared login limit across both replicas with 429/Retry-After
|
||||||
|
PASS: TLS telemetry query succeeds and logs exclude test password/session token
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
groups:
|
||||||
|
- name: messenger
|
||||||
|
interval: 5s
|
||||||
|
rules:
|
||||||
|
- alert: MessengerHighErrors
|
||||||
|
expr: sum(rate(http_requests_total{status_class="5xx",route!~"/health/.*"}[1m])) / clamp_min(sum(rate(http_requests_total{route!~"/health/.*"}[1m])),0.001) > 0.2
|
||||||
|
for: 10s
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
annotations:
|
||||||
|
summary: API error ratio exceeds 20 percent
|
||||||
|
description: Inspect postgresql.transaction spans and db_pool_waiting. Restore db and verify ready.
|
||||||
|
- alert: MessengerQueueLag
|
||||||
|
expr: max(queue{measurement="oldest_seconds"}) > 10
|
||||||
|
for: 10s
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
annotations:
|
||||||
|
summary: Oldest unfinished job is older than ten seconds
|
||||||
|
description: Inspect worker_busy, jobs_processed_total and worker logs. Restore worker and verify backlog drains.
|
||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
mkdir -p /tmp/db-tls
|
||||||
|
cp /tls/cert.pem /tls/key.pem /tmp/db-tls/
|
||||||
|
chown -R postgres:postgres /tmp/db-tls
|
||||||
|
chmod 600 /tmp/db-tls/key.pem
|
||||||
|
exec docker-entrypoint.sh "$@"
|
||||||
@@ -0,0 +1,401 @@
|
|||||||
|
{
|
||||||
|
"uid": "messenger",
|
||||||
|
"title": "Messenger",
|
||||||
|
"schemaVersion": 40,
|
||||||
|
"panels": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "RPS",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "reqps"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 0,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "sum(rate(http_requests_total{route!~\"/health/.*\"}[1m]))",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Server error ratio",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 0,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "sum(rate(http_requests_total{status_class=\"5xx\",route!~\"/health/.*\"}[1m])) / clamp_min(sum(rate(http_requests_total{route!~\"/health/.*\"}[1m])),0.001)",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "HTTP p50",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 8,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_duration_seconds_bucket[1m])))",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "HTTP p95",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 8,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_duration_seconds_bucket[1m])))",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "HTTP p99",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 16,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_duration_seconds_bucket[1m])))",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"title": "Jobs by outcome",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "ops"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 16,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "sum by(outcome)(rate(jobs_processed_total[1m]))",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 7,
|
||||||
|
"title": "Worker p95",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 24,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "histogram_quantile(0.95,sum by(le)(rate(job_duration_seconds_bucket[1m])))",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 8,
|
||||||
|
"title": "Time to ready p95",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 24,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "histogram_quantile(0.95,sum by(le)(rate(attachment_ready_duration_seconds_bucket[1m])))",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 9,
|
||||||
|
"title": "Queue depth",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 32,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "max(queue{measurement=\"depth\"})",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 10,
|
||||||
|
"title": "Oldest job",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 32,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "max(queue{measurement=\"oldest_seconds\"})",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 11,
|
||||||
|
"title": "DB pool used",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 40,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "db_pool_used",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 12,
|
||||||
|
"title": "DB pool waiting",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 40,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "db_pool_waiting",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 13,
|
||||||
|
"title": "Worker busy",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 48,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "worker_busy",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 14,
|
||||||
|
"title": "Process peak RSS",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "bytes"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 48,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "process_memory_bytes",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 15,
|
||||||
|
"title": "Process CPU",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"uid": "prometheus",
|
||||||
|
"type": "prometheus"
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 56,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "rate(process_cpu_seconds_total[1m])",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"time": {
|
||||||
|
"from": "now-15m",
|
||||||
|
"to": "now"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
providers:
|
||||||
|
- name: Messenger
|
||||||
|
type: file
|
||||||
|
options:
|
||||||
|
path: /var/lib/grafana/dashboards
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
global
|
||||||
|
log stdout format raw local0
|
||||||
|
|
||||||
|
defaults
|
||||||
|
mode http
|
||||||
|
log global
|
||||||
|
option httplog
|
||||||
|
option http-server-close
|
||||||
|
timeout connect 1s
|
||||||
|
timeout client 15s
|
||||||
|
timeout server 12s
|
||||||
|
timeout http-request 8s
|
||||||
|
timeout check 1s
|
||||||
|
retries 0
|
||||||
|
|
||||||
|
resolvers docker
|
||||||
|
nameserver dns 127.0.0.11:53
|
||||||
|
resolve_retries 2
|
||||||
|
timeout resolve 500ms
|
||||||
|
timeout retry 500ms
|
||||||
|
hold valid 1s
|
||||||
|
hold nx 1s
|
||||||
|
|
||||||
|
frontend messenger
|
||||||
|
bind :8443 ssl crt /tls/bundle.pem
|
||||||
|
default_backend api
|
||||||
|
|
||||||
|
backend api
|
||||||
|
balance roundrobin
|
||||||
|
option httpchk GET /health/ready
|
||||||
|
http-check expect status 200
|
||||||
|
default-server check inter 1s fall 2 rise 1 resolvers docker resolve-prefer ipv4 init-addr libc,none
|
||||||
|
server api-a api-a:8443 ssl verify required ca-file /tls/ca.pem crt /tls/bundle.pem verifyhost api-a
|
||||||
|
server api-b api-b:8443 ssl verify required ca-file /tls/ca.pem crt /tls/bundle.pem verifyhost api-b
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
auth_enabled: false
|
||||||
|
server:
|
||||||
|
http_listen_port: 3100
|
||||||
|
http_listen_address: 127.0.0.1
|
||||||
|
grpc_listen_address: 127.0.0.1
|
||||||
|
common:
|
||||||
|
path_prefix: /loki
|
||||||
|
replication_factor: 1
|
||||||
|
ring:
|
||||||
|
kvstore:
|
||||||
|
store: inmemory
|
||||||
|
storage:
|
||||||
|
filesystem:
|
||||||
|
chunks_directory: /loki/chunks
|
||||||
|
rules_directory: /loki/rules
|
||||||
|
instance_addr: 127.0.0.1
|
||||||
|
schema_config:
|
||||||
|
configs:
|
||||||
|
- from: 2024-01-01
|
||||||
|
store: tsdb
|
||||||
|
object_store: filesystem
|
||||||
|
schema: v13
|
||||||
|
index:
|
||||||
|
prefix: index_
|
||||||
|
period: 24h
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
|
||||||
|
ui = true
|
||||||
|
disable_mlock = true
|
||||||
|
storage "file" { path = "/bao/data" }
|
||||||
|
listener "tcp" {
|
||||||
|
address = "0.0.0.0:8200"
|
||||||
|
tls_cert_file = "/tls/cert.pem"
|
||||||
|
tls_key_file = "/tls/key.pem"
|
||||||
|
tls_client_ca_file = "/tls/ca.pem"
|
||||||
|
}
|
||||||
|
api_addr = "https://openbao:8200"
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 127.0.0.1:4318
|
||||||
|
processors:
|
||||||
|
memory_limiter:
|
||||||
|
check_interval: 1s
|
||||||
|
limit_mib: 128
|
||||||
|
spike_limit_mib: 32
|
||||||
|
batch:
|
||||||
|
send_batch_size: 128
|
||||||
|
timeout: 2s
|
||||||
|
exporters:
|
||||||
|
prometheus:
|
||||||
|
endpoint: 127.0.0.1:8889
|
||||||
|
resource_to_telemetry_conversion:
|
||||||
|
enabled: true
|
||||||
|
otlphttp/tempo:
|
||||||
|
endpoint: https://tempo:4319
|
||||||
|
sending_queue:
|
||||||
|
queue_size: 128
|
||||||
|
retry_on_failure:
|
||||||
|
max_elapsed_time: 10s
|
||||||
|
max_interval: 5s
|
||||||
|
tls:
|
||||||
|
ca_file: /tls/ca.pem
|
||||||
|
cert_file: /tls/cert.pem
|
||||||
|
key_file: /tls/key.pem
|
||||||
|
otlphttp/loki:
|
||||||
|
endpoint: https://loki:3101/otlp
|
||||||
|
sending_queue:
|
||||||
|
queue_size: 128
|
||||||
|
retry_on_failure:
|
||||||
|
max_elapsed_time: 10s
|
||||||
|
max_interval: 5s
|
||||||
|
tls:
|
||||||
|
ca_file: /tls/ca.pem
|
||||||
|
cert_file: /tls/cert.pem
|
||||||
|
key_file: /tls/key.pem
|
||||||
|
service:
|
||||||
|
pipelines:
|
||||||
|
metrics:
|
||||||
|
receivers:
|
||||||
|
- otlp
|
||||||
|
processors:
|
||||||
|
- memory_limiter
|
||||||
|
- batch
|
||||||
|
exporters:
|
||||||
|
- prometheus
|
||||||
|
traces:
|
||||||
|
receivers:
|
||||||
|
- otlp
|
||||||
|
processors:
|
||||||
|
- memory_limiter
|
||||||
|
- batch
|
||||||
|
exporters:
|
||||||
|
- otlphttp/tempo
|
||||||
|
logs:
|
||||||
|
receivers:
|
||||||
|
- otlp
|
||||||
|
processors:
|
||||||
|
- memory_limiter
|
||||||
|
- batch
|
||||||
|
exporters:
|
||||||
|
- otlphttp/loki
|
||||||
|
telemetry:
|
||||||
|
metrics:
|
||||||
|
level: none
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
local all all trust
|
||||||
|
hostssl all all all scram-sha-256
|
||||||
|
hostnossl all all all reject
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
global:
|
||||||
|
scrape_interval: 5s
|
||||||
|
scrape_configs:
|
||||||
|
- job_name: messenger
|
||||||
|
scheme: https
|
||||||
|
static_configs:
|
||||||
|
- targets:
|
||||||
|
- otel-collector:8890
|
||||||
|
tls_config:
|
||||||
|
ca_file: /tls/ca.pem
|
||||||
|
cert_file: /tls/cert.pem
|
||||||
|
key_file: /tls/key.pem
|
||||||
|
server_name: otel-collector
|
||||||
|
rule_files:
|
||||||
|
- /etc/prometheus/alerts.yaml
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
server:
|
||||||
|
http_listen_port: 3200
|
||||||
|
http_listen_address: 127.0.0.1
|
||||||
|
grpc_listen_address: 127.0.0.1
|
||||||
|
distributor:
|
||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 127.0.0.1:4318
|
||||||
|
storage:
|
||||||
|
trace:
|
||||||
|
backend: local
|
||||||
|
local:
|
||||||
|
path: /var/tempo/traces
|
||||||
|
wal:
|
||||||
|
path: /var/tempo/wal
|
||||||
|
compactor:
|
||||||
|
compaction:
|
||||||
|
block_retention: 24h
|
||||||
|
ingester:
|
||||||
|
lifecycler:
|
||||||
|
address: 127.0.0.1
|
||||||
|
ring:
|
||||||
|
kvstore:
|
||||||
|
store: inmemory
|
||||||
|
replication_factor: 1
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"listen": 8443,
|
||||||
|
"backend": 8080,
|
||||||
|
"clients": {
|
||||||
|
"lb": [],
|
||||||
|
"operator": [
|
||||||
|
"GET"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"listen": 8443,
|
||||||
|
"backend": 8080,
|
||||||
|
"clients": {
|
||||||
|
"lb": [],
|
||||||
|
"operator": [
|
||||||
|
"GET"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"listen": 6380,
|
||||||
|
"backend": 6379,
|
||||||
|
"clients": {
|
||||||
|
"worker": [],
|
||||||
|
"dispatcher": []
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"listen": 6380,
|
||||||
|
"backend": 6379,
|
||||||
|
"clients": {
|
||||||
|
"api-a": [],
|
||||||
|
"api-b": [],
|
||||||
|
"worker": [],
|
||||||
|
"dispatcher": []
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"listen": 3101,
|
||||||
|
"backend": 3100,
|
||||||
|
"clients": {
|
||||||
|
"otel-collector": [
|
||||||
|
"POST"
|
||||||
|
],
|
||||||
|
"grafana": [
|
||||||
|
"GET"
|
||||||
|
],
|
||||||
|
"operator": [
|
||||||
|
"GET"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"listen": 4319,
|
||||||
|
"backend": 4318,
|
||||||
|
"clients": {
|
||||||
|
"api-a": [
|
||||||
|
"POST"
|
||||||
|
],
|
||||||
|
"api-b": [
|
||||||
|
"POST"
|
||||||
|
],
|
||||||
|
"worker": [
|
||||||
|
"POST"
|
||||||
|
],
|
||||||
|
"dispatcher": [
|
||||||
|
"POST"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"listen": 8890,
|
||||||
|
"backend": 8889,
|
||||||
|
"clients": {
|
||||||
|
"prometheus": [
|
||||||
|
"GET"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"listen": 9091,
|
||||||
|
"backend": 9090,
|
||||||
|
"clients": {
|
||||||
|
"grafana": [
|
||||||
|
"GET"
|
||||||
|
],
|
||||||
|
"operator": [
|
||||||
|
"GET"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"listen": 9002,
|
||||||
|
"backend": 9000,
|
||||||
|
"clients": {
|
||||||
|
"api-a": [
|
||||||
|
"HEAD",
|
||||||
|
"GET",
|
||||||
|
"PUT"
|
||||||
|
],
|
||||||
|
"api-b": [
|
||||||
|
"HEAD",
|
||||||
|
"GET",
|
||||||
|
"PUT"
|
||||||
|
],
|
||||||
|
"worker": [
|
||||||
|
"HEAD",
|
||||||
|
"GET",
|
||||||
|
"PUT",
|
||||||
|
"DELETE"
|
||||||
|
],
|
||||||
|
"s3-init": [
|
||||||
|
"HEAD",
|
||||||
|
"GET",
|
||||||
|
"PUT"
|
||||||
|
],
|
||||||
|
"operator": [
|
||||||
|
"HEAD",
|
||||||
|
"GET",
|
||||||
|
"PUT",
|
||||||
|
"DELETE"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"write_prefixes": {
|
||||||
|
"api-a": "/messenger-attachments/staging/",
|
||||||
|
"api-b": "/messenger-attachments/staging/"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"listen": 4319,
|
||||||
|
"backend": 4318,
|
||||||
|
"clients": {
|
||||||
|
"otel-collector": [
|
||||||
|
"POST"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"listen": 3201,
|
||||||
|
"backend": 3200,
|
||||||
|
"clients": {
|
||||||
|
"grafana": [
|
||||||
|
"GET"
|
||||||
|
],
|
||||||
|
"operator": [
|
||||||
|
"GET"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
CREATE TABLE users (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||||
|
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||||
|
password_hash bytea NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE chats (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE members (
|
||||||
|
chat_id uuid REFERENCES chats(id),
|
||||||
|
user_id uuid REFERENCES users(id),
|
||||||
|
position integer NOT NULL,
|
||||||
|
PRIMARY KEY (chat_id, user_id),
|
||||||
|
UNIQUE (chat_id, position)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX members_user_idx ON members (user_id, chat_id);
|
||||||
|
CREATE INDEX chats_order_idx ON chats (created_at, id);
|
||||||
|
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
chat_id uuid NOT NULL,
|
||||||
|
sender_id uuid NOT NULL,
|
||||||
|
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
FOREIGN KEY (chat_id, sender_id) REFERENCES members (chat_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
|
||||||
|
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
token_hash bytea PRIMARY KEY,
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id),
|
||||||
|
expires_at timestamptz NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
CREATE TABLE message_requests (
|
||||||
|
actor_id uuid NOT NULL REFERENCES users(id),
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||||
|
key text NOT NULL,
|
||||||
|
fingerprint bytea NOT NULL,
|
||||||
|
message_id uuid NOT NULL REFERENCES messages(id),
|
||||||
|
expires_at timestamptz NOT NULL,
|
||||||
|
PRIMARY KEY (actor_id, chat_id, key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX message_requests_expiry_idx ON message_requests (expires_at);
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
CREATE TABLE attachments (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
chat_id uuid NOT NULL,
|
||||||
|
owner_id uuid NOT NULL,
|
||||||
|
filename text NOT NULL,
|
||||||
|
content_type text NOT NULL,
|
||||||
|
size_bytes integer NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||||
|
sha256 text NOT NULL,
|
||||||
|
ready boolean NOT NULL DEFAULT false,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
FOREIGN KEY (chat_id, owner_id) REFERENCES members (chat_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE NOT ready;
|
||||||
|
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
|
||||||
|
ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}';
|
||||||
|
ALTER TABLE messages ADD CHECK (char_length(text) <= 4000 AND
|
||||||
|
cardinality(attachment_ids) <= 10 AND (char_length(text) > 0 OR cardinality(attachment_ids) > 0));
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
ALTER TABLE attachments ADD COLUMN status text NOT NULL DEFAULT 'receiving'
|
||||||
|
CHECK (status IN ('receiving','queued','processing','ready','failed'));
|
||||||
|
UPDATE attachments SET status='ready' WHERE ready;
|
||||||
|
ALTER TABLE attachments ADD COLUMN variants jsonb NOT NULL DEFAULT '[]';
|
||||||
|
ALTER TABLE attachments ADD COLUMN error_code text;
|
||||||
|
CREATE TABLE jobs (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id),
|
||||||
|
attempt integer NOT NULL DEFAULT 0,
|
||||||
|
next_attempt timestamptz NOT NULL DEFAULT now(),
|
||||||
|
published_at timestamptz,
|
||||||
|
lease_until timestamptz,
|
||||||
|
finished boolean NOT NULL DEFAULT false
|
||||||
|
);
|
||||||
|
CREATE TABLE job_replays (
|
||||||
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
job_id uuid NOT NULL REFERENCES jobs(id),
|
||||||
|
replayed_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE jobs ADD COLUMN trace_context jsonb NOT NULL DEFAULT '{}';
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
CREATE TABLE login_limits (
|
||||||
|
key bytea PRIMARY KEY,
|
||||||
|
count integer NOT NULL,
|
||||||
|
window_start timestamptz NOT NULL
|
||||||
|
);
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
cryptography==50.0.0
|
||||||
|
PyYAML==6.0.3
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
argon2-cffi==25.1.0
|
||||||
|
argon2-cffi-bindings==26.2.0
|
||||||
|
boto3==1.39.3
|
||||||
|
botocore==1.39.3
|
||||||
|
certifi==2026.11.20
|
||||||
|
cffi==2.1.1
|
||||||
|
charset-normalizer==3.5.3
|
||||||
|
cryptography==50.0.0
|
||||||
|
googleapis-common-protos==1.76.0
|
||||||
|
idna==3.20
|
||||||
|
jmespath==1.0.1
|
||||||
|
opentelemetry-api==1.45.2
|
||||||
|
opentelemetry-exporter-http-transport==0.66b2
|
||||||
|
opentelemetry-exporter-otlp-common==0.66b2
|
||||||
|
opentelemetry-exporter-otlp-proto-common==1.45.2
|
||||||
|
opentelemetry-exporter-otlp-proto-http==1.45.2
|
||||||
|
opentelemetry-proto==1.45.2
|
||||||
|
opentelemetry-sdk==1.45.2
|
||||||
|
opentelemetry-semantic-conventions==0.66b2
|
||||||
|
pillow==13.0.0
|
||||||
|
protobuf==7.36.2
|
||||||
|
psycopg==3.2.9
|
||||||
|
psycopg-binary==3.2.9
|
||||||
|
psycopg-pool==3.2.6
|
||||||
|
pycparser==3.12
|
||||||
|
python-dateutil==2.9.0.post0
|
||||||
|
redis==6.2.0
|
||||||
|
requests==2.34.2
|
||||||
|
s3transfer==0.13.0
|
||||||
|
six==1.17.0
|
||||||
|
typing_extensions==4.14.0
|
||||||
|
urllib3==2.8.0
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
directory = ROOT / "secrets"
|
||||||
|
statements = ["REVOKE ALL ON SCHEMA public FROM PUBLIC;"]
|
||||||
|
for role in ("api", "worker", "dispatcher"):
|
||||||
|
password = (directory / f"db_{role}_password").read_text().strip().replace("'", "''")
|
||||||
|
statements.append(f"""
|
||||||
|
DO $$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='{role}')
|
||||||
|
THEN CREATE ROLE {role} LOGIN; END IF; END $$;
|
||||||
|
ALTER ROLE {role} PASSWORD '{password}';
|
||||||
|
GRANT CONNECT ON DATABASE messenger TO {role};
|
||||||
|
GRANT USAGE ON SCHEMA public TO {role};
|
||||||
|
""")
|
||||||
|
statements += [
|
||||||
|
"GRANT SELECT ON users,chats,members,messages,sessions,attachments,jobs,message_requests,login_limits TO api;",
|
||||||
|
"GRANT SELECT ON attachments,jobs TO worker;",
|
||||||
|
"GRANT SELECT ON attachments,jobs TO dispatcher;",
|
||||||
|
"GRANT SELECT(id) ON users TO worker,dispatcher;",
|
||||||
|
"GRANT INSERT,UPDATE,DELETE ON users,chats,members,messages,sessions,attachments,jobs,message_requests,login_limits TO api;",
|
||||||
|
"GRANT UPDATE ON attachments,jobs TO worker;",
|
||||||
|
"GRANT UPDATE ON jobs TO dispatcher;",
|
||||||
|
"GRANT INSERT,SELECT ON job_replays TO api;",
|
||||||
|
"GRANT USAGE ON SEQUENCE job_replays_id_seq TO api;",
|
||||||
|
]
|
||||||
|
subprocess.run(["docker", "compose", "exec", "-T", "db", "psql", "-v",
|
||||||
|
"ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger"],
|
||||||
|
cwd=ROOT, input="\n".join(statements), text=True, check=True,
|
||||||
|
stdout=subprocess.DEVNULL)
|
||||||
|
print("Scoped database roles configured")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
command = (
|
||||||
|
"pip install --quiet --target /tmp/audit pip-audit==2.9.0 >/dev/null && "
|
||||||
|
"PYTHONPATH=/tmp/audit python -m pip_audit "
|
||||||
|
"--path /usr/local/lib/python3.13/site-packages --cache-dir /tmp/cache "
|
||||||
|
"--format json --progress-spinner off"
|
||||||
|
)
|
||||||
|
with (ROOT / "evidence/dependency-audit.json").open("wb") as output:
|
||||||
|
result = subprocess.run([
|
||||||
|
"docker", "run", "--rm", "-e", "XDG_CACHE_HOME=/tmp/cache",
|
||||||
|
"--entrypoint", "sh", "mtusi-messenger:lab7", "-c", command,
|
||||||
|
], stdout=output, check=False)
|
||||||
|
raise SystemExit(result.returncode)
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from urllib.error import URLError
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
OPERATOR = ROOT / "secrets" / "operator"
|
||||||
|
ADDRESS = "https://localhost:18207"
|
||||||
|
|
||||||
|
|
||||||
|
def request(path, data=None, token=None, method=None):
|
||||||
|
context = ssl.create_default_context(cafile=str(OPERATOR / "ca.pem"))
|
||||||
|
context.load_cert_chain(ROOT / "secrets/tls/operator/cert.pem", ROOT / "secrets/tls/operator/key.pem")
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
if token:
|
||||||
|
headers["X-Vault-Token"] = token
|
||||||
|
req = Request(ADDRESS + "/v1/" + path,
|
||||||
|
data=json.dumps(data).encode() if data is not None else None,
|
||||||
|
headers=headers, method=method)
|
||||||
|
with urlopen(req, context=context, timeout=5) as response:
|
||||||
|
return json.load(response) if response.status != 204 else {}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
state_path = OPERATOR / "bao-init.json"
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
request("sys/init")
|
||||||
|
break
|
||||||
|
except URLError as error:
|
||||||
|
if isinstance(error.reason, ssl.SSLCertVerificationError) or time.monotonic() >= deadline:
|
||||||
|
raise
|
||||||
|
time.sleep(0.5)
|
||||||
|
if not request("sys/init")["initialized"]:
|
||||||
|
state = request("sys/init", {"secret_shares": 1, "secret_threshold": 1}, method="PUT")
|
||||||
|
state_path.write_text(json.dumps(state))
|
||||||
|
state_path.chmod(0o600)
|
||||||
|
state = json.loads(state_path.read_text())
|
||||||
|
if request("sys/seal-status")["sealed"]:
|
||||||
|
request("sys/unseal", {"key": state["keys"][0]}, method="PUT")
|
||||||
|
token = state["root_token"]
|
||||||
|
if len(sys.argv) > 1 and sys.argv[1] == "seal":
|
||||||
|
request("sys/seal", {}, token, "PUT")
|
||||||
|
print("OpenBao sealed")
|
||||||
|
return
|
||||||
|
if "secret/" not in request("sys/mounts", token=token):
|
||||||
|
request("sys/mounts/secret", {"type": "kv", "options": {"version": "2"}}, token)
|
||||||
|
if "cert/" not in request("sys/auth", token=token):
|
||||||
|
request("sys/auth/cert", {"type": "cert"}, token)
|
||||||
|
if (OPERATOR / "crl.pem").exists():
|
||||||
|
request("auth/cert/crls/lab", {"crl": (OPERATOR / "crl.pem").read_text()}, token)
|
||||||
|
for service, values in json.loads((OPERATOR / "kv-bootstrap.json").read_text()).items():
|
||||||
|
policy = f'path "secret/data/{service}" {{ capabilities = ["read"] }}'
|
||||||
|
request("sys/policies/acl/" + service, {"policy": policy}, token, "PUT")
|
||||||
|
request("auth/cert/certs/" + service, {
|
||||||
|
"certificate": (OPERATOR / "ca.pem").read_text(),
|
||||||
|
"allowed_dns_sans": [service], "token_policies": [service],
|
||||||
|
"token_ttl": 60, "token_max_ttl": 120,
|
||||||
|
}, token)
|
||||||
|
request("secret/data/" + service, {"data": values}, token)
|
||||||
|
print("OpenBao initialized, unsealed and scoped policies configured")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+161
@@ -0,0 +1,161 @@
|
|||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
import ipaddress
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from cryptography import x509
|
||||||
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||||
|
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
OPERATOR = ROOT / "secrets" / "operator"
|
||||||
|
TLS = ROOT / "secrets" / "tls"
|
||||||
|
SERVICES = ("api-a", "api-b", "worker", "dispatcher", "migrate", "s3-init", "lb",
|
||||||
|
"db", "broker", "cache", "s3", "otel-collector", "prometheus", "loki",
|
||||||
|
"tempo", "grafana", "openbao", "operator", "foreign")
|
||||||
|
|
||||||
|
|
||||||
|
def save_key(path, key):
|
||||||
|
path.write_bytes(key.private_bytes(serialization.Encoding.PEM,
|
||||||
|
serialization.PrivateFormat.PKCS8,
|
||||||
|
serialization.NoEncryption()))
|
||||||
|
path.chmod(0o644 if TLS in path.parents else 0o600)
|
||||||
|
|
||||||
|
|
||||||
|
def has_identifiers(path):
|
||||||
|
if not path.exists():
|
||||||
|
return False
|
||||||
|
cert = x509.load_pem_x509_certificate(path.read_bytes())
|
||||||
|
try:
|
||||||
|
cert.extensions.get_extension_for_class(x509.AuthorityKeyIdentifier)
|
||||||
|
return True
|
||||||
|
except x509.ExtensionNotFound:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def initialize():
|
||||||
|
OPERATOR.mkdir(parents=True, exist_ok=True)
|
||||||
|
if not (OPERATOR / "ca-key.pem").exists() or not has_identifiers(OPERATOR / "ca.pem"):
|
||||||
|
if (OPERATOR / "ca-key.pem").exists():
|
||||||
|
key = serialization.load_pem_private_key((OPERATOR / "ca-key.pem").read_bytes(), password=None)
|
||||||
|
else:
|
||||||
|
key = rsa.generate_private_key(public_exponent=65537, key_size=3072)
|
||||||
|
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "MTUSI Lab CA")])
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
|
||||||
|
.public_key(key.public_key()).serial_number(x509.random_serial_number())
|
||||||
|
.not_valid_before(now - timedelta(minutes=5)).not_valid_after(now + timedelta(days=365))
|
||||||
|
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
|
||||||
|
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False)
|
||||||
|
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()), critical=False)
|
||||||
|
.add_extension(x509.KeyUsage(True,False,False,False,False,True,True,False,False), critical=True)
|
||||||
|
.sign(key, hashes.SHA256()))
|
||||||
|
save_key(OPERATOR / "ca-key.pem", key)
|
||||||
|
(OPERATOR / "ca.pem").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||||
|
for service in SERVICES:
|
||||||
|
if not has_identifiers(TLS / service / "cert.pem"):
|
||||||
|
issue(service)
|
||||||
|
directory = TLS / "untrusted"
|
||||||
|
if not directory.exists():
|
||||||
|
directory.mkdir()
|
||||||
|
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||||
|
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Untrusted test identity")])
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
|
||||||
|
.public_key(key.public_key()).serial_number(x509.random_serial_number())
|
||||||
|
.not_valid_before(now-timedelta(minutes=1)).not_valid_after(now+timedelta(days=1))
|
||||||
|
.add_extension(x509.SubjectAlternativeName([x509.DNSName("lb")]),critical=False)
|
||||||
|
.add_extension(x509.BasicConstraints(ca=False,path_length=None),critical=True)
|
||||||
|
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),critical=False)
|
||||||
|
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]),critical=False)
|
||||||
|
.sign(key,hashes.SHA256()))
|
||||||
|
directory.joinpath("cert.pem").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||||
|
save_key(directory/"key.pem",key)
|
||||||
|
directory = TLS / "expired"
|
||||||
|
if not directory.exists():
|
||||||
|
directory.mkdir()
|
||||||
|
ca_key = serialization.load_pem_private_key((OPERATOR/"ca-key.pem").read_bytes(),password=None)
|
||||||
|
ca = x509.load_pem_x509_certificate((OPERATOR/"ca.pem").read_bytes())
|
||||||
|
key = rsa.generate_private_key(public_exponent=65537,key_size=2048)
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
cert = (x509.CertificateBuilder()
|
||||||
|
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,"lb")]))
|
||||||
|
.issuer_name(ca.subject).public_key(key.public_key()).serial_number(x509.random_serial_number())
|
||||||
|
.not_valid_before(now-timedelta(hours=2)).not_valid_after(now-timedelta(hours=1))
|
||||||
|
.add_extension(x509.SubjectAlternativeName([x509.DNSName("lb")]),critical=False)
|
||||||
|
.add_extension(x509.BasicConstraints(ca=False,path_length=None),critical=True)
|
||||||
|
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()),critical=False)
|
||||||
|
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]),critical=False)
|
||||||
|
.sign(ca_key,hashes.SHA256()))
|
||||||
|
directory.joinpath("cert.pem").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||||
|
save_key(directory/"key.pem",key)
|
||||||
|
|
||||||
|
|
||||||
|
def issue(service):
|
||||||
|
if service not in SERVICES:
|
||||||
|
raise ValueError("Unknown service")
|
||||||
|
key = serialization.load_pem_private_key((OPERATOR / "ca-key.pem").read_bytes(), password=None)
|
||||||
|
ca = x509.load_pem_x509_certificate((OPERATOR / "ca.pem").read_bytes())
|
||||||
|
leaf_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
names = [x509.DNSName(service)]
|
||||||
|
if service in ("lb", "openbao", "grafana"):
|
||||||
|
names += [x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]
|
||||||
|
cert = (x509.CertificateBuilder()
|
||||||
|
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, service)]))
|
||||||
|
.issuer_name(ca.subject).public_key(leaf_key.public_key())
|
||||||
|
.serial_number(x509.random_serial_number())
|
||||||
|
.not_valid_before(now - timedelta(minutes=1)).not_valid_after(now + timedelta(hours=24))
|
||||||
|
.add_extension(x509.SubjectAlternativeName(names), critical=False)
|
||||||
|
.add_extension(x509.BasicConstraints(ca=False,path_length=None), critical=True)
|
||||||
|
.add_extension(x509.SubjectKeyIdentifier.from_public_key(leaf_key.public_key()), critical=False)
|
||||||
|
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()), critical=False)
|
||||||
|
.add_extension(x509.KeyUsage(True,False,True,False,False,False,False,False,False), critical=True)
|
||||||
|
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH,
|
||||||
|
ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False)
|
||||||
|
.sign(key, hashes.SHA256()))
|
||||||
|
directory = TLS / service
|
||||||
|
directory.mkdir(parents=True, exist_ok=True)
|
||||||
|
directory.joinpath("ca.pem").write_bytes((OPERATOR / "ca.pem").read_bytes())
|
||||||
|
directory.joinpath("cert.pem").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||||
|
save_key(directory / "key.pem", leaf_key)
|
||||||
|
directory.joinpath("bundle.pem").write_bytes(
|
||||||
|
directory.joinpath("cert.pem").read_bytes() + directory.joinpath("key.pem").read_bytes())
|
||||||
|
if not directory.joinpath("revoked.json").exists():
|
||||||
|
directory.joinpath("revoked.json").write_text("[]")
|
||||||
|
|
||||||
|
|
||||||
|
def revoke(service):
|
||||||
|
cert = x509.load_pem_x509_certificate((TLS / service / "cert.pem").read_bytes())
|
||||||
|
serial = format(cert.serial_number, "x")
|
||||||
|
registry = OPERATOR / "revocations.json"
|
||||||
|
revoked = json.loads(registry.read_text()) if registry.exists() else []
|
||||||
|
if serial not in revoked:
|
||||||
|
revoked.append(serial)
|
||||||
|
registry.write_text(json.dumps(revoked))
|
||||||
|
ca = x509.load_pem_x509_certificate((OPERATOR / "ca.pem").read_bytes())
|
||||||
|
key = serialization.load_pem_private_key((OPERATOR / "ca-key.pem").read_bytes(), password=None)
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
crl = x509.CertificateRevocationListBuilder().issuer_name(ca.subject)
|
||||||
|
crl = crl.last_update(now).next_update(now + timedelta(days=1))
|
||||||
|
for value in revoked:
|
||||||
|
crl = crl.add_revoked_certificate(x509.RevokedCertificateBuilder()
|
||||||
|
.serial_number(int(value, 16)).revocation_date(now).build())
|
||||||
|
(OPERATOR / "crl.pem").write_bytes(crl.sign(key, hashes.SHA256()).public_bytes(serialization.Encoding.PEM))
|
||||||
|
for directory in TLS.iterdir():
|
||||||
|
path = directory / "revoked.json"
|
||||||
|
values = json.loads(path.read_text()) if path.exists() else []
|
||||||
|
if serial not in values:
|
||||||
|
values.append(serial)
|
||||||
|
path.write_text(json.dumps(values))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
initialize()
|
||||||
|
if len(sys.argv) == 3 and sys.argv[1] == "rotate":
|
||||||
|
revoke(sys.argv[2])
|
||||||
|
issue(sys.argv[2])
|
||||||
|
elif len(sys.argv) == 3 and sys.argv[1] == "revoke":
|
||||||
|
revoke(sys.argv[2])
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0.."
|
||||||
|
docker compose restart db cache broker s3 openbao prometheus loki tempo grafana otel-collector
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
python scripts/bao_operator.py
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
docker compose restart cache-tls broker-tls s3-tls otel-collector-tls-otlp otel-collector-tls-scrape prometheus-tls loki-tls tempo-tls-query tempo-tls-otlp
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
docker compose restart dispatcher worker api-a api-b
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
docker compose restart api-a-tls api-b-tls lb
|
||||||
Executable
+8
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
docker compose restart db cache broker s3 openbao prometheus loki tempo grafana otel-collector
|
||||||
|
python3 scripts/bao_operator.py
|
||||||
|
docker compose restart cache-tls broker-tls s3-tls otel-collector-tls-otlp otel-collector-tls-scrape prometheus-tls loki-tls tempo-tls-query tempo-tls-otlp
|
||||||
|
docker compose restart dispatcher worker api-a api-b
|
||||||
|
docker compose restart api-a-tls api-b-tls lb
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import secrets
|
||||||
|
from shutil import copyfile
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from pki import ROOT, TLS, issue, revoke
|
||||||
|
|
||||||
|
|
||||||
|
def run(*args):
|
||||||
|
subprocess.run(args, cwd=ROOT, check=True, timeout=90, stdout=subprocess.DEVNULL)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
mode = sys.argv[1]
|
||||||
|
if mode == "secret":
|
||||||
|
path = ROOT / "secrets/db_api_password"
|
||||||
|
path.write_text(secrets.token_hex(24))
|
||||||
|
run(sys.executable, "scripts/security_setup.py")
|
||||||
|
run(sys.executable, "scripts/apply_roles.py")
|
||||||
|
run(sys.executable, "scripts/bao_operator.py")
|
||||||
|
run("docker", "compose", "restart", "api-a", "api-b")
|
||||||
|
run("docker", "compose", "restart", "api-a-tls", "api-b-tls")
|
||||||
|
print("Rotated API database credential without rebuilding images")
|
||||||
|
elif mode == "certificate":
|
||||||
|
saved = TLS / "revoked-api-a"
|
||||||
|
saved.mkdir(exist_ok=True)
|
||||||
|
for name in ("cert.pem", "key.pem", "ca.pem"):
|
||||||
|
copyfile(TLS / "api-a" / name, saved / name)
|
||||||
|
revoke("api-a")
|
||||||
|
issue("api-a")
|
||||||
|
run(sys.executable, "scripts/bao_operator.py")
|
||||||
|
run("docker", "compose", "restart", "api-a", "api-a-tls")
|
||||||
|
print("Rotated API leaf certificate and revoked previous identity")
|
||||||
|
else:
|
||||||
|
raise SystemExit("Usage: python scripts/rotate.py secret|certificate")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import secrets
|
||||||
|
import yaml
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from pki import initialize, ROOT
|
||||||
|
|
||||||
|
|
||||||
|
def ensure(name):
|
||||||
|
path = ROOT / "secrets" / name
|
||||||
|
if not path.exists():
|
||||||
|
path.write_text(secrets.token_hex(24))
|
||||||
|
return path.read_text().strip()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
initialize()
|
||||||
|
directory = ROOT / "secrets"
|
||||||
|
directory.chmod(0o700)
|
||||||
|
admin_password = (directory / "db_password").read_text().strip()
|
||||||
|
roles = {"api-a": "api", "api-b": "api", "worker": "worker", "dispatcher": "dispatcher"}
|
||||||
|
passwords = {role: ensure("db_" + role + "_password") for role in set(roles.values())}
|
||||||
|
broker_passwords = {role: ensure("broker_" + role + "_password") for role in ("worker", "dispatcher")}
|
||||||
|
cache_password = ensure("cache_password")
|
||||||
|
bucket = "messenger-attachments"
|
||||||
|
app_key = (directory / "s3_access_key_id").read_text().strip()
|
||||||
|
app_secret = (directory / "s3_secret_access_key").read_text().strip()
|
||||||
|
worker_key = "worker-" + ensure("worker_s3_id")[:16]
|
||||||
|
worker_secret = ensure("worker_s3_secret")
|
||||||
|
values = {}
|
||||||
|
for service, role in roles.items():
|
||||||
|
values[service] = {
|
||||||
|
"DATABASE_URL": f"postgresql://{role}:{quote(passwords[role],safe='')}@db:5432/messenger?sslmode=verify-full&sslrootcert=/tls/ca.pem",
|
||||||
|
"CACHE_URL": f"rediss://profiles:{cache_password}@cache:6380/0",
|
||||||
|
"CURSOR_KEY": (directory / "cursor_key").read_text().strip(),
|
||||||
|
}
|
||||||
|
if service in broker_passwords:
|
||||||
|
values[service]["BROKER_URL"] = f"rediss://{service}:{broker_passwords[service]}@broker:6380/0"
|
||||||
|
if service != "dispatcher":
|
||||||
|
values[service].update(S3_ACCESS_KEY_ID=worker_key if service == "worker" else app_key,
|
||||||
|
S3_SECRET_ACCESS_KEY=worker_secret if service == "worker" else app_secret)
|
||||||
|
(directory / "operator" / "kv-bootstrap.json").write_text(json.dumps(values))
|
||||||
|
config_path = directory / "s3_config"
|
||||||
|
config = json.loads(config_path.read_text())
|
||||||
|
config["identities"][1]["actions"] = [f"Read:{bucket}", f"List:{bucket}", f"Write:{bucket}"]
|
||||||
|
config["identities"] = [entry for entry in config["identities"] if entry["name"] != "worker"]
|
||||||
|
config["identities"].append({
|
||||||
|
"name": "worker",
|
||||||
|
"credentials": [{"accessKey": worker_key, "secretKey": worker_secret}],
|
||||||
|
"actions": [f"Read:{bucket}", f"Write:{bucket}", f"List:{bucket}"],
|
||||||
|
})
|
||||||
|
config_path.write_text(json.dumps(config))
|
||||||
|
(directory / "broker.acl").write_text(
|
||||||
|
f"user default off\n"
|
||||||
|
f"user dispatcher on >{broker_passwords['dispatcher']} ~images +xadd +ping\n"
|
||||||
|
f"user worker on >{broker_passwords['worker']} ~images +xgroup +xautoclaim +xreadgroup +xack +xdel +ping\n")
|
||||||
|
(directory / "cache.acl").write_text(
|
||||||
|
f"user default off\nuser profiles on >{cache_password} ~user:v1:* +get +setex +ping\n")
|
||||||
|
(directory / "database_url").write_text(
|
||||||
|
f"postgresql://messenger:{quote(admin_password,safe='')}@db:5432/messenger?sslmode=verify-full&sslrootcert=/tls/ca.pem")
|
||||||
|
(ROOT / "infra" / "tls").mkdir(exist_ok=True)
|
||||||
|
(ROOT / "infra" / "openbao.hcl").write_text("""
|
||||||
|
ui = true
|
||||||
|
disable_mlock = true
|
||||||
|
storage "file" { path = "/bao/data" }
|
||||||
|
listener "tcp" {
|
||||||
|
address = "0.0.0.0:8200"
|
||||||
|
tls_cert_file = "/tls/cert.pem"
|
||||||
|
tls_key_file = "/tls/key.pem"
|
||||||
|
tls_client_ca_file = "/tls/ca.pem"
|
||||||
|
}
|
||||||
|
api_addr = "https://openbao:8200"
|
||||||
|
""")
|
||||||
|
(directory / "grafana_password").write_text(ensure("grafana_admin_password"))
|
||||||
|
tls = directory / "tls" / "grafana"
|
||||||
|
sources = []
|
||||||
|
for name, kind, endpoint in (
|
||||||
|
("Prometheus", "prometheus", "https://prometheus:9091"),
|
||||||
|
("Loki", "loki", "https://loki:3101"),
|
||||||
|
("Tempo", "tempo", "https://tempo:3201"),
|
||||||
|
):
|
||||||
|
sources.append({
|
||||||
|
"name": name, "uid": kind, "type": kind, "url": endpoint,
|
||||||
|
"isDefault": kind == "prometheus",
|
||||||
|
"jsonData": {"tlsAuth": True, "tlsAuthWithCACert": True,
|
||||||
|
**({"httpMethod": "GET"} if kind == "prometheus" else {})},
|
||||||
|
"secureJsonData": {"tlsCACert": (tls / "ca.pem").read_text(),
|
||||||
|
"tlsClientCert": (tls / "cert.pem").read_text(),
|
||||||
|
"tlsClientKey": (tls / "key.pem").read_text()},
|
||||||
|
})
|
||||||
|
(directory / "grafana-datasources.yaml").write_text(yaml.safe_dump(
|
||||||
|
{"apiVersion": 1, "datasources": sources}))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
root = Path(__file__).resolve().parents[1]
|
||||||
|
directory = root / "secrets"
|
||||||
|
directory.mkdir(mode=0o700, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def ensure(name, value):
|
||||||
|
path = directory / name
|
||||||
|
try:
|
||||||
|
with path.open("x", encoding="utf-8") as file:
|
||||||
|
file.write(value + "\n")
|
||||||
|
except FileExistsError:
|
||||||
|
pass
|
||||||
|
return path.read_text(encoding="utf-8").strip()
|
||||||
|
|
||||||
|
|
||||||
|
password = ensure("db_password", secrets.token_hex(24))
|
||||||
|
ensure("database_url", f"postgresql://messenger:{password}@db:5432/messenger")
|
||||||
|
ensure("cache_url", "redis://cache:6379/0")
|
||||||
|
ensure("cursor_key", secrets.token_hex(32))
|
||||||
|
ensure("broker_url", "redis://broker:6379/0")
|
||||||
|
admin = ensure("s3_admin_access_key", "admin-" + secrets.token_hex(8))
|
||||||
|
admin_password = ensure("s3_admin_secret_key", secrets.token_hex(24))
|
||||||
|
app = ensure("s3_access_key_id", "app-" + secrets.token_hex(8))
|
||||||
|
app_password = ensure("s3_secret_access_key", secrets.token_hex(20))
|
||||||
|
|
||||||
|
try:
|
||||||
|
with (root / ".env").open("xb") as file:
|
||||||
|
file.write((root / ".env.example").read_bytes())
|
||||||
|
except FileExistsError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
env = dict(
|
||||||
|
line.split("=", 1) for line in (root / ".env").read_text(encoding="utf-8").splitlines()
|
||||||
|
if line and not line.startswith("#") and "=" in line
|
||||||
|
)
|
||||||
|
bucket = env["S3_BUCKET"]
|
||||||
|
config = {"identities": [
|
||||||
|
{"name": "bootstrap", "credentials": [{"accessKey": admin, "secretKey": admin_password}],
|
||||||
|
"actions": ["Admin"]},
|
||||||
|
{"name": "messenger", "credentials": [{"accessKey": app, "secretKey": app_password}],
|
||||||
|
"actions": [f"Read:{bucket}", f"Write:{bucket}", f"List:{bucket}"]},
|
||||||
|
]}
|
||||||
|
(directory / "s3_config").write_text(json.dumps(config) + "\n", encoding="utf-8")
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import ssl
|
||||||
|
import time
|
||||||
|
from urllib.error import URLError
|
||||||
|
from urllib.request import urlopen
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
def run(*args):
|
||||||
|
subprocess.run(args, cwd=ROOT, check=True, timeout=300)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run(sys.executable, "scripts/setup.py")
|
||||||
|
run(sys.executable, "scripts/security_setup.py")
|
||||||
|
run("docker", "compose", "build", "migrate")
|
||||||
|
run("docker", "compose", "up", "-d", "db", "cache", "broker", "s3", "s3-tls",
|
||||||
|
"cache-tls", "broker-tls", "openbao")
|
||||||
|
run("docker", "compose", "up", "-d", "--no-deps", "--force-recreate",
|
||||||
|
"s3-tls", "cache-tls", "broker-tls")
|
||||||
|
run(sys.executable, "scripts/bao_operator.py")
|
||||||
|
run("docker", "compose", "run", "--rm", "migrate")
|
||||||
|
run(sys.executable, "scripts/apply_roles.py")
|
||||||
|
run("docker", "compose", "up", "-d", "--wait", "--wait-timeout", "120")
|
||||||
|
run("docker", "compose", "up", "-d", "--no-deps", "--force-recreate",
|
||||||
|
"api-a-tls", "api-b-tls", "otel-collector-tls-otlp",
|
||||||
|
"otel-collector-tls-scrape", "prometheus-tls", "loki-tls",
|
||||||
|
"tempo-tls-query", "tempo-tls-otlp")
|
||||||
|
context = ssl.create_default_context(cafile=str(ROOT / "secrets/operator/ca.pem"))
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
with urlopen("https://localhost:18443/health/ready", context=context, timeout=3):
|
||||||
|
break
|
||||||
|
except URLError:
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
raise
|
||||||
|
time.sleep(0.5)
|
||||||
|
print("HTTPS stack is ready")
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0.."
|
||||||
|
for %%S in (api-a api-b) do (
|
||||||
|
for /f "delims=" %%I in ('docker compose exec -T %%S cat /tmp/instance-id') do (
|
||||||
|
if "%%I"=="%TARGET_INSTANCE_ID%" (
|
||||||
|
docker compose stop --timeout 5 %%S
|
||||||
|
exit /b
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
exit /b 2
|
||||||
Executable
+11
@@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
for service in api-a api-b; do
|
||||||
|
alias=$(docker compose exec -T "$service" cat /tmp/instance-id)
|
||||||
|
if [ "$alias" = "$TARGET_INSTANCE_ID" ]; then
|
||||||
|
docker compose stop --timeout 5 "$service"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
exit 2
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
from contextlib import contextmanager
|
||||||
|
from telemetry import operation
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
import unicodedata
|
||||||
|
from tempfile import TemporaryFile
|
||||||
|
from threading import BoundedSemaphore
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
from botocore.config import Config
|
||||||
|
from botocore.exceptions import BotoCoreError, ClientError
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from config import positive_int, secret
|
||||||
|
from storage import unavailable
|
||||||
|
from opentelemetry.propagate import inject
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
from validation import ApiError, invalid, not_found
|
||||||
|
|
||||||
|
MIME_FORMATS = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
||||||
|
S3_ERRORS = (BotoCoreError, ClientError)
|
||||||
|
CHUNK = 64 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
class TracedS3:
|
||||||
|
def __init__(self, client):
|
||||||
|
self.client = client
|
||||||
|
|
||||||
|
def __getattr__(self, name):
|
||||||
|
method = getattr(self.client, name)
|
||||||
|
def call(**kwargs):
|
||||||
|
with operation("s3." + name):
|
||||||
|
return method(**kwargs)
|
||||||
|
return call
|
||||||
|
|
||||||
|
|
||||||
|
class Attachments:
|
||||||
|
def __init__(self, store):
|
||||||
|
self.store = store
|
||||||
|
self.bucket = os.environ["S3_BUCKET"]
|
||||||
|
self.max_bytes = min(positive_int("MAX_UPLOAD_BYTES", 10485760), 10485760)
|
||||||
|
self.max_pixels = min(positive_int("MAX_IMAGE_PIXELS", 40000000), 40000000)
|
||||||
|
self.slots = BoundedSemaphore(2)
|
||||||
|
self.s3 = TracedS3(boto3.client(
|
||||||
|
"s3", verify="/tls/ca.pem", endpoint_url=os.environ["S3_ENDPOINT"], region_name=os.environ["S3_REGION"],
|
||||||
|
aws_access_key_id=secret("S3_ACCESS_KEY_ID"), aws_secret_access_key=secret("S3_SECRET_ACCESS_KEY"),
|
||||||
|
config=Config(client_cert=("/tls/cert.pem","/tls/key.pem"), connect_timeout=1, read_timeout=3, retries={"total_max_attempts": 1},
|
||||||
|
request_checksum_calculation="when_required", s3={"addressing_style": "path"}),
|
||||||
|
))
|
||||||
|
|
||||||
|
def ready(self):
|
||||||
|
try:
|
||||||
|
self.s3.head_bucket(Bucket=self.bucket)
|
||||||
|
except S3_ERRORS:
|
||||||
|
raise unavailable() from None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def key(attachment_id):
|
||||||
|
return f"attachments/{attachment_id}"
|
||||||
|
|
||||||
|
def upload(self, request, actor, chat_id, filename):
|
||||||
|
if (not 1 <= len(filename) <= 255 or filename in (".", "..")
|
||||||
|
or any(c in "/\\" or unicodedata.category(c) in ("Cc", "Cs") for c in filename)):
|
||||||
|
raise invalid("Invalid filename")
|
||||||
|
content_type = request.headers.get_content_type()
|
||||||
|
if content_type not in MIME_FORMATS:
|
||||||
|
raise ApiError(415, "unsupported_media_type", "Expected PNG or JPEG")
|
||||||
|
lengths = request.headers.get_all("Content-Length", [])
|
||||||
|
if (request.headers.get("Transfer-Encoding") or len(lengths) != 1
|
||||||
|
or not re.fullmatch(r"[0-9]{1,19}", lengths[0])):
|
||||||
|
raise invalid("Content-Length required")
|
||||||
|
length = int(lengths[0])
|
||||||
|
if length > self.max_bytes:
|
||||||
|
raise ApiError(413, "payload_too_large", "Attachment is too large")
|
||||||
|
if not self.slots.acquire(timeout=2):
|
||||||
|
raise unavailable()
|
||||||
|
try:
|
||||||
|
with TemporaryFile() as file:
|
||||||
|
checksum = self.receive(request, file, length)
|
||||||
|
self.validate(file, content_type)
|
||||||
|
attachment_id = uuid4()
|
||||||
|
self.reserve(attachment_id, chat_id, actor, filename, content_type, length, checksum)
|
||||||
|
try:
|
||||||
|
self.s3.put_object(Bucket=self.bucket, Key="staging/" + str(attachment_id),
|
||||||
|
Body=file, ContentLength=length, ContentType=content_type)
|
||||||
|
except S3_ERRORS:
|
||||||
|
raise unavailable() from None
|
||||||
|
with self.store.pool.connection() as db:
|
||||||
|
row = db.execute("""
|
||||||
|
UPDATE attachments SET status='queued',updated_at=clock_timestamp()
|
||||||
|
WHERE id=%s RETURNING *
|
||||||
|
""", (attachment_id,)).fetchone()
|
||||||
|
carrier = {}
|
||||||
|
inject(carrier)
|
||||||
|
db.execute("INSERT INTO jobs (attachment_id,trace_context) VALUES (%s,%s)",
|
||||||
|
(attachment_id, Jsonb(carrier)))
|
||||||
|
return self.public(row)
|
||||||
|
finally:
|
||||||
|
self.slots.release()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def receive(request, file, length):
|
||||||
|
checksum = hashlib.sha256()
|
||||||
|
deadline = time.monotonic() + 10
|
||||||
|
remaining = length
|
||||||
|
while remaining:
|
||||||
|
if time.monotonic() > deadline:
|
||||||
|
raise ApiError(408, "invalid_request", "Upload timed out")
|
||||||
|
chunk = request.rfile.read1(min(CHUNK, remaining))
|
||||||
|
if not chunk:
|
||||||
|
raise invalid("Incomplete attachment")
|
||||||
|
file.write(chunk)
|
||||||
|
checksum.update(chunk)
|
||||||
|
remaining -= len(chunk)
|
||||||
|
file.seek(0)
|
||||||
|
return checksum.hexdigest()
|
||||||
|
|
||||||
|
def validate(self, file, content_type):
|
||||||
|
try:
|
||||||
|
with Image.open(file, formats=[MIME_FORMATS[content_type]]) as image:
|
||||||
|
if image.width * image.height > self.max_pixels:
|
||||||
|
raise ApiError(413, "payload_too_large", "Image pixel limit exceeded")
|
||||||
|
image.verify()
|
||||||
|
file.seek(0)
|
||||||
|
with Image.open(file, formats=[MIME_FORMATS[content_type]]) as image:
|
||||||
|
image.load()
|
||||||
|
except Image.DecompressionBombError:
|
||||||
|
raise ApiError(413, "payload_too_large", "Image pixel limit exceeded") from None
|
||||||
|
except (OSError, ValueError, SyntaxError, EOFError):
|
||||||
|
raise ApiError(415, "unsupported_media_type", "Invalid image") from None
|
||||||
|
file.seek(0)
|
||||||
|
|
||||||
|
def reserve(self, attachment_id, chat_id, actor, filename, content_type, length, checksum):
|
||||||
|
with self.store.pool.connection() as db:
|
||||||
|
db.execute("""
|
||||||
|
INSERT INTO attachments (id,chat_id,owner_id,filename,content_type,size_bytes,sha256)
|
||||||
|
VALUES (%s,%s,%s,%s,%s,%s,%s)
|
||||||
|
""", (attachment_id, chat_id, actor, filename, content_type, length, checksum))
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def public(row):
|
||||||
|
return {**{name: value for name, value in row.items() if name not in ("ready", "variants")},
|
||||||
|
"variants": row["variants"]}
|
||||||
|
|
||||||
|
def get(self, actor, attachment_id):
|
||||||
|
with self.store.pool.connection() as db:
|
||||||
|
row = db.execute("""
|
||||||
|
SELECT a.* FROM attachments a JOIN members m ON m.chat_id=a.chat_id
|
||||||
|
WHERE a.id=%s AND a.status <> 'receiving' AND m.user_id=%s
|
||||||
|
""", (attachment_id, actor)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise not_found()
|
||||||
|
return self.public(row)
|
||||||
|
|
||||||
|
def download(self, attachment):
|
||||||
|
if attachment["status"] != "ready":
|
||||||
|
raise ApiError(409, "conflict", "Attachment is not ready")
|
||||||
|
try:
|
||||||
|
result = self.s3.get_object(Bucket=self.bucket, Key=self.key(attachment["id"]))
|
||||||
|
except S3_ERRORS:
|
||||||
|
raise unavailable() from None
|
||||||
|
if result["ContentLength"] != attachment["size_bytes"]:
|
||||||
|
result["Body"].close()
|
||||||
|
raise unavailable()
|
||||||
|
return result["Body"]
|
||||||
|
|
||||||
|
def cleanup(self):
|
||||||
|
count = 0
|
||||||
|
while True:
|
||||||
|
with self.store.pool.connection() as db:
|
||||||
|
row = db.execute("""
|
||||||
|
SELECT id FROM attachments
|
||||||
|
WHERE status='receiving' AND created_at < now() - interval '1 day'
|
||||||
|
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED
|
||||||
|
""").fetchone()
|
||||||
|
if row is None:
|
||||||
|
return count
|
||||||
|
attachment_id = row["id"]
|
||||||
|
self.s3.delete_object(Bucket=self.bucket, Key="staging/" + str(attachment_id))
|
||||||
|
db.execute("DELETE FROM attachments WHERE id=%s", (attachment_id,))
|
||||||
|
count += 1
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import time
|
||||||
|
from threading import Lock
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
|
LOCK = Lock()
|
||||||
|
CACHED = {}
|
||||||
|
|
||||||
|
|
||||||
|
def context():
|
||||||
|
result = ssl.create_default_context(cafile="/tls/ca.pem")
|
||||||
|
result.load_cert_chain("/tls/cert.pem", "/tls/key.pem")
|
||||||
|
result.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def read_secret(name):
|
||||||
|
service = os.environ["SERVICE_ID"]
|
||||||
|
with LOCK:
|
||||||
|
if CACHED.get("expires", 0) <= time.monotonic():
|
||||||
|
request = Request("https://openbao:8200/v1/auth/cert/login",
|
||||||
|
data=json.dumps({"name": service}).encode(),
|
||||||
|
headers={"Content-Type": "application/json"})
|
||||||
|
with urlopen(request, context=context(), timeout=3) as response:
|
||||||
|
auth = json.load(response)["auth"]
|
||||||
|
token = auth["client_token"]
|
||||||
|
request = Request(f"https://openbao:8200/v1/secret/data/{service}",
|
||||||
|
headers={"X-Vault-Token": token})
|
||||||
|
with urlopen(request, context=context(), timeout=3) as response:
|
||||||
|
values = json.load(response)["data"]["data"]
|
||||||
|
CACHED.update(values=values, expires=time.monotonic() + min(15, auth["lease_duration"]))
|
||||||
|
return CACHED["values"][name]
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
from botocore.config import Config
|
||||||
|
from botocore.exceptions import ClientError, BotoCoreError
|
||||||
|
|
||||||
|
from config import secret
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
bucket = os.environ["S3_BUCKET"]
|
||||||
|
s3 = boto3.client(
|
||||||
|
"s3", verify="/tls/ca.pem", endpoint_url=os.environ["S3_ENDPOINT"], region_name=os.environ["S3_REGION"],
|
||||||
|
aws_access_key_id=secret("S3_ADMIN_ACCESS_KEY"),
|
||||||
|
aws_secret_access_key=secret("S3_ADMIN_SECRET_KEY"),
|
||||||
|
config=Config(client_cert=("/tls/cert.pem","/tls/key.pem"), connect_timeout=1, read_timeout=2, retries={"total_max_attempts": 1},
|
||||||
|
request_checksum_calculation="when_required", s3={"addressing_style": "path"}),
|
||||||
|
)
|
||||||
|
deadline = time.monotonic() + 90
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
s3.head_bucket(Bucket=bucket)
|
||||||
|
break
|
||||||
|
except ClientError as error:
|
||||||
|
if error.response["ResponseMetadata"]["HTTPStatusCode"] != 404:
|
||||||
|
raise
|
||||||
|
try:
|
||||||
|
s3.create_bucket(Bucket=bucket)
|
||||||
|
except ClientError as conflict:
|
||||||
|
if conflict.response["Error"]["Code"] != "BucketAlreadyOwnedByYou":
|
||||||
|
raise
|
||||||
|
break
|
||||||
|
except BotoCoreError:
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
raise
|
||||||
|
time.sleep(0.5)
|
||||||
|
print("Private S3 bucket is ready")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
from attachments import Attachments
|
||||||
|
from storage import Store
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
store = Store()
|
||||||
|
try:
|
||||||
|
print(f"Removed unfinished uploads: {Attachments(store).cleanup()}")
|
||||||
|
finally:
|
||||||
|
store.close()
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def secret(name):
|
||||||
|
if os.getenv("SERVICE_ID") in ("api-a", "api-b", "worker", "dispatcher"):
|
||||||
|
from bao_client import read_secret
|
||||||
|
return read_secret(name)
|
||||||
|
return Path(os.environ[name + "_FILE"]).read_text(encoding="utf-8").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def positive_int(name, default):
|
||||||
|
value = int(os.getenv(name, default))
|
||||||
|
if value < 1:
|
||||||
|
raise ValueError(f"{name} must be positive")
|
||||||
|
return value
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
from datetime import datetime, timezone
|
||||||
|
import logging
|
||||||
|
from telemetry import configure, operation, observe_queue
|
||||||
|
from opentelemetry import trace
|
||||||
|
from opentelemetry.propagate import extract, inject
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
|
import redis
|
||||||
|
|
||||||
|
from config import secret
|
||||||
|
from storage import Store
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
configure("messenger-dispatcher")
|
||||||
|
store = Store()
|
||||||
|
observe_queue(store)
|
||||||
|
broker = redis.Redis.from_url(secret("BROKER_URL"), ssl_ca_certs="/tls/ca.pem", ssl_certfile="/tls/cert.pem", ssl_keyfile="/tls/key.pem", socket_timeout=2)
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
with store.pool.connection() as db:
|
||||||
|
rows = db.execute("""
|
||||||
|
SELECT id,attachment_id,attempt,trace_context FROM jobs WHERE NOT finished AND next_attempt <= now()
|
||||||
|
AND (lease_until IS NULL OR lease_until < now())
|
||||||
|
AND (published_at IS NULL OR published_at < now() - interval '30 seconds')
|
||||||
|
ORDER BY next_attempt LIMIT 10 FOR UPDATE SKIP LOCKED
|
||||||
|
""").fetchall()
|
||||||
|
for row in rows:
|
||||||
|
if os.getenv("CRASH_BEFORE_PUBLISH") == "1":
|
||||||
|
os._exit(18)
|
||||||
|
payload = {
|
||||||
|
"schema_version": 1, "job_id": str(row["id"]),
|
||||||
|
"attachment_id": str(row["attachment_id"]), "pipeline_version": 1,
|
||||||
|
"type": "attachment.process.v1", "attempt": row["attempt"] + 1,
|
||||||
|
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||||
|
}
|
||||||
|
with operation("images.publish", trace.SpanKind.PRODUCER, extract(row["trace_context"])):
|
||||||
|
inject(payload)
|
||||||
|
broker.xadd("images", {"payload": json.dumps(payload)})
|
||||||
|
db.execute("UPDATE jobs SET published_at=now() WHERE id=%s", (row["id"],))
|
||||||
|
time.sleep(0.25)
|
||||||
|
except Exception:
|
||||||
|
logging.warning("dispatch unavailable")
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
import psycopg
|
||||||
|
from config import secret
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
with psycopg.connect(secret("DATABASE_URL"), connect_timeout=3) as connection:
|
||||||
|
connection.execute("SELECT pg_advisory_xact_lock(230301)")
|
||||||
|
connection.execute("CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY)")
|
||||||
|
for path in sorted(Path("migrations").glob("*.sql")):
|
||||||
|
if connection.execute("SELECT 1 FROM schema_migrations WHERE name=%s", (path.name,)).fetchone():
|
||||||
|
continue
|
||||||
|
connection.execute(path.read_text(encoding="utf-8"))
|
||||||
|
connection.execute("INSERT INTO schema_migrations (name) VALUES (%s)", (path.name,))
|
||||||
|
print(f"Applied {path.name}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
from concurrent.futures import Future, TimeoutError
|
||||||
|
from queue import Empty, Full, Queue
|
||||||
|
from threading import Event, Thread
|
||||||
|
|
||||||
|
import redis
|
||||||
|
from redis.backoff import NoBackoff
|
||||||
|
from redis.retry import Retry
|
||||||
|
|
||||||
|
|
||||||
|
class ProfileCache:
|
||||||
|
def __init__(self, url):
|
||||||
|
self.client = redis.Redis.from_url(
|
||||||
|
url, socket_timeout=0.25, socket_connect_timeout=0.25,
|
||||||
|
ssl_ca_certs="/tls/ca.pem", ssl_certfile="/tls/cert.pem", ssl_keyfile="/tls/key.pem",
|
||||||
|
max_connections=1, retry=Retry(NoBackoff(), 0),
|
||||||
|
)
|
||||||
|
self.work = Queue(maxsize=4)
|
||||||
|
self.stopping = Event()
|
||||||
|
Thread(target=self.run, daemon=True, name="profile-cache").start()
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.stopping.set()
|
||||||
|
|
||||||
|
def run(self):
|
||||||
|
try:
|
||||||
|
while not self.stopping.is_set():
|
||||||
|
try:
|
||||||
|
result, operation, args = self.work.get(timeout=0.25)
|
||||||
|
except Empty:
|
||||||
|
continue
|
||||||
|
if not result.set_running_or_notify_cancel():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
result.set_result(operation(*args))
|
||||||
|
except redis.RedisError:
|
||||||
|
result.set_result(None)
|
||||||
|
finally:
|
||||||
|
self.client.close()
|
||||||
|
|
||||||
|
def submit(self, operation, *args):
|
||||||
|
result = Future()
|
||||||
|
try:
|
||||||
|
self.work.put_nowait((result, operation, args))
|
||||||
|
except Full:
|
||||||
|
result.set_result(None)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def get(self, key):
|
||||||
|
result = self.submit(self.client.get, key)
|
||||||
|
try:
|
||||||
|
return result.result(timeout=0.35)
|
||||||
|
except TimeoutError:
|
||||||
|
result.cancel()
|
||||||
|
return None
|
||||||
|
|
||||||
|
def set(self, key, value):
|
||||||
|
self.submit(self.client.setex, key, 300, value)
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import sys
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from storage import Store
|
||||||
|
|
||||||
|
|
||||||
|
def main(job_id):
|
||||||
|
store = Store()
|
||||||
|
try:
|
||||||
|
with store.pool.connection() as db:
|
||||||
|
job = db.execute("""
|
||||||
|
SELECT j.id,j.attachment_id FROM jobs j JOIN attachments a ON a.id=j.attachment_id
|
||||||
|
WHERE j.id=%s AND j.finished AND a.status='failed' FOR UPDATE OF j,a
|
||||||
|
""", (UUID(job_id),)).fetchone()
|
||||||
|
if job is None:
|
||||||
|
raise SystemExit("Only failed jobs can be replayed")
|
||||||
|
db.execute("INSERT INTO job_replays (job_id) VALUES (%s)", (job["id"],))
|
||||||
|
db.execute("""
|
||||||
|
UPDATE jobs SET finished=false,attempt=0,published_at=NULL,lease_until=NULL,
|
||||||
|
next_attempt=now() WHERE id=%s
|
||||||
|
""", (job["id"],))
|
||||||
|
db.execute("UPDATE attachments SET status='queued',error_code=NULL WHERE id=%s",
|
||||||
|
(job["attachment_id"],))
|
||||||
|
finally:
|
||||||
|
store.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main(sys.argv[1])
|
||||||
+378
@@ -0,0 +1,378 @@
|
|||||||
|
import time
|
||||||
|
from telemetry import configure, operation, route_template, http_count, http_duration
|
||||||
|
from opentelemetry import trace
|
||||||
|
from opentelemetry.propagate import extract
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import signal
|
||||||
|
import threading
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from urllib.parse import parse_qs, unquote, urlsplit
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from attachments import Attachments, S3_ERRORS
|
||||||
|
from storage import DB_UNAVAILABLE, Store, json_value, unauthorized, unavailable
|
||||||
|
from validation import ApiError, canonical_id, invalid, not_found, require_fields, require_text
|
||||||
|
|
||||||
|
CHAT_PATH = re.compile(r"/api/v1/chats/([^/]+)(?:/(messages|attachments))?")
|
||||||
|
ATTACHMENT_PATH = re.compile(r"/api/v1/attachments/([^/]+)(/content)?")
|
||||||
|
MAX_JSON_BYTES = 64 * 1024
|
||||||
|
LOG = logging.getLogger("messenger")
|
||||||
|
|
||||||
|
|
||||||
|
def unique_object(pairs):
|
||||||
|
result = dict(pairs)
|
||||||
|
if len(result) != len(pairs):
|
||||||
|
raise ValueError
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def page_query(query):
|
||||||
|
try:
|
||||||
|
params = parse_qs(query, keep_blank_values=True, max_num_fields=16)
|
||||||
|
except ValueError:
|
||||||
|
raise invalid("Invalid query") from None
|
||||||
|
limits = params.get("limit", ["50"])
|
||||||
|
cursors = params.get("cursor", [None])
|
||||||
|
if len(limits) != 1 or not re.fullmatch(r"[0-9]{1,3}", limits[0]):
|
||||||
|
raise invalid("Invalid limit")
|
||||||
|
limit = int(limits[0])
|
||||||
|
if not 1 <= limit <= 100:
|
||||||
|
raise invalid("Invalid limit")
|
||||||
|
if len(cursors) != 1:
|
||||||
|
raise invalid("Invalid cursor")
|
||||||
|
return limit, cursors[0]
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
def do_GET(self):
|
||||||
|
self.handle_api()
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
self.handle_api()
|
||||||
|
|
||||||
|
def do_DELETE(self):
|
||||||
|
self.handle_api()
|
||||||
|
|
||||||
|
def log_message(self, format, *args):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def log_request(self, code="-", size="-"):
|
||||||
|
LOG.info("request_id=%s status=%s", self.request_id, code)
|
||||||
|
|
||||||
|
def send_error(self, code, message=None, explain=None):
|
||||||
|
self.request_id = uuid4().hex
|
||||||
|
self.response_headers = {}
|
||||||
|
self.send_json(code, {"error": {
|
||||||
|
"code": "invalid_request",
|
||||||
|
"message": "Invalid HTTP request",
|
||||||
|
"request_id": self.request_id,
|
||||||
|
}})
|
||||||
|
|
||||||
|
def handle_api(self):
|
||||||
|
started = time.monotonic()
|
||||||
|
route = route_template(self.path)
|
||||||
|
self.telemetry_status = 500
|
||||||
|
with operation(route, trace.SpanKind.SERVER, extract(dict(self.headers))):
|
||||||
|
trace.get_current_span().set_attribute("http.route", route)
|
||||||
|
self.handle_instrumented()
|
||||||
|
trace.get_current_span().set_attribute("http.response.status_code", self.telemetry_status)
|
||||||
|
if self.telemetry_status >= 500:
|
||||||
|
trace.get_current_span().set_status(trace.StatusCode.ERROR)
|
||||||
|
attributes = {"method": self.command, "route": route,
|
||||||
|
"status_class": str(self.telemetry_status // 100) + "xx"}
|
||||||
|
http_count.add(1, attributes)
|
||||||
|
http_duration.record(time.monotonic() - started, attributes)
|
||||||
|
|
||||||
|
def handle_instrumented(self):
|
||||||
|
self.request_id = uuid4().hex
|
||||||
|
self.response_headers = {}
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
status, payload = self.route()
|
||||||
|
except ApiError as error:
|
||||||
|
status, payload = self.error_payload(error)
|
||||||
|
except DB_UNAVAILABLE:
|
||||||
|
status, payload = self.error_payload(unavailable())
|
||||||
|
except (TimeoutError, ConnectionError):
|
||||||
|
return
|
||||||
|
except Exception:
|
||||||
|
LOG.error("request_id=%s unexpected error", self.request_id)
|
||||||
|
status, payload = self.error_payload(
|
||||||
|
ApiError(500, "internal_error", "Internal server error")
|
||||||
|
)
|
||||||
|
if isinstance(payload, tuple):
|
||||||
|
self.send_attachment(*payload)
|
||||||
|
else:
|
||||||
|
self.send_json(status, payload)
|
||||||
|
except (TimeoutError, ConnectionError, *S3_ERRORS):
|
||||||
|
return
|
||||||
|
|
||||||
|
def error_payload(self, error):
|
||||||
|
self.response_headers = error.headers
|
||||||
|
return error.status, {"error": {
|
||||||
|
"code": error.code,
|
||||||
|
"message": str(error),
|
||||||
|
"request_id": self.request_id,
|
||||||
|
}}
|
||||||
|
|
||||||
|
def send_json(self, status, payload):
|
||||||
|
self.telemetry_status = status
|
||||||
|
data = b"" if status == 204 else json.dumps(payload, ensure_ascii=False, default=json_value).encode("utf-8")
|
||||||
|
self.send_response(status)
|
||||||
|
self.send_header("X-Request-Id", self.request_id)
|
||||||
|
self.send_header("X-Instance-Id", self.server.instance_id)
|
||||||
|
if status != 204:
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
for name, value in self.response_headers.items():
|
||||||
|
self.send_header(name, value)
|
||||||
|
self.send_header("Content-Length", str(len(data)))
|
||||||
|
self.end_headers()
|
||||||
|
if self.command != "HEAD":
|
||||||
|
self.wfile.write(data)
|
||||||
|
|
||||||
|
def send_attachment(self, stream, attachment):
|
||||||
|
self.telemetry_status = 200
|
||||||
|
with stream:
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("X-Request-Id", self.request_id)
|
||||||
|
self.send_header("X-Instance-Id", self.server.instance_id)
|
||||||
|
self.send_header("Content-Type", attachment["content_type"])
|
||||||
|
self.send_header("Content-Length", str(attachment["size_bytes"]))
|
||||||
|
self.end_headers()
|
||||||
|
for chunk in stream.iter_chunks(64 * 1024):
|
||||||
|
self.wfile.write(chunk)
|
||||||
|
|
||||||
|
def read_json(self):
|
||||||
|
lengths = self.headers.get_all("Content-Length", [])
|
||||||
|
if (
|
||||||
|
self.headers.get("Transfer-Encoding")
|
||||||
|
or len(lengths) != 1
|
||||||
|
or not re.fullmatch(r"[0-9]{1,10}", lengths[0])
|
||||||
|
or self.headers.get_content_type() != "application/json"
|
||||||
|
):
|
||||||
|
raise invalid("Expected a JSON body")
|
||||||
|
length = int(lengths[0])
|
||||||
|
if length > MAX_JSON_BYTES:
|
||||||
|
raise invalid("JSON body is too large")
|
||||||
|
try:
|
||||||
|
data = self.rfile.read(length)
|
||||||
|
if len(data) != length:
|
||||||
|
raise ValueError
|
||||||
|
return json.loads(data.decode("utf-8"), object_pairs_hook=unique_object)
|
||||||
|
except (ValueError, RecursionError):
|
||||||
|
raise invalid("Invalid JSON") from None
|
||||||
|
|
||||||
|
def route(self):
|
||||||
|
try:
|
||||||
|
target = urlsplit(self.path)
|
||||||
|
except ValueError:
|
||||||
|
raise invalid("Invalid request path") from None
|
||||||
|
path, method = target.path, self.command
|
||||||
|
app = self.server.app
|
||||||
|
|
||||||
|
if method == "GET" and path == "/health/live":
|
||||||
|
return 200, {"status": "ok"}
|
||||||
|
if method == "GET" and path == "/health/ready":
|
||||||
|
app.ready()
|
||||||
|
self.server.attachments.ready()
|
||||||
|
return 200, {"status": "ok"}
|
||||||
|
if method == "POST" and path == "/api/v1/users":
|
||||||
|
body = self.read_json()
|
||||||
|
require_fields(body, "username", "display_name", "password")
|
||||||
|
username = body["username"]
|
||||||
|
if not isinstance(username, str) or not re.fullmatch(r"[a-z0-9_]{3,32}", username):
|
||||||
|
raise invalid("Invalid username")
|
||||||
|
password = body["password"]
|
||||||
|
if not isinstance(password, str) or not 12 <= len(password) <= 128:
|
||||||
|
raise invalid("Invalid password")
|
||||||
|
try:
|
||||||
|
password.encode("utf-8")
|
||||||
|
except UnicodeError:
|
||||||
|
raise invalid("Invalid password") from None
|
||||||
|
return 201, app.register(username, require_text(body["display_name"], 100), password)
|
||||||
|
if method == "POST" and path == "/api/v1/auth/sessions":
|
||||||
|
return 201, app.login(*self.basic_credentials())
|
||||||
|
|
||||||
|
match = CHAT_PATH.fullmatch(path)
|
||||||
|
attachment_match = ATTACHMENT_PATH.fullmatch(path)
|
||||||
|
if path not in ("/api/v1/users/me", "/api/v1/chats", "/api/v1/auth/sessions/current") and not (match or attachment_match):
|
||||||
|
raise not_found()
|
||||||
|
header = self.headers.get("Authorization", "")
|
||||||
|
bearer = re.fullmatch(r"(?i:Bearer) ([A-Za-z0-9_-]{43})", header)
|
||||||
|
if not bearer:
|
||||||
|
raise unauthorized("Bearer")
|
||||||
|
digest = app.token_hash(bearer[1])
|
||||||
|
actor = app.actor(digest)
|
||||||
|
if path == "/api/v1/auth/sessions/current" and method == "DELETE":
|
||||||
|
app.logout(digest)
|
||||||
|
return 204, None
|
||||||
|
if path == "/api/v1/users/me" and method == "GET":
|
||||||
|
return 200, app.user(actor)
|
||||||
|
if path == "/api/v1/chats":
|
||||||
|
if method == "POST":
|
||||||
|
body = self.read_json()
|
||||||
|
require_fields(body, "title", "member_ids")
|
||||||
|
title = require_text(body["title"], 100)
|
||||||
|
members = body["member_ids"]
|
||||||
|
if not isinstance(members, list) or not 1 <= len(members) <= 100:
|
||||||
|
raise invalid("Invalid member list")
|
||||||
|
members = [canonical_id(member) for member in members]
|
||||||
|
if actor not in members or len(set(members)) != len(members):
|
||||||
|
raise invalid("Invalid member list")
|
||||||
|
return 201, app.create_chat(title, members)
|
||||||
|
if method == "GET":
|
||||||
|
return 200, app.chat_page(actor, *page_query(target.query))
|
||||||
|
if attachment_match and method == "GET":
|
||||||
|
attachment_id = canonical_id(unquote(attachment_match[1]))
|
||||||
|
attachment = self.server.attachments.get(actor, attachment_id)
|
||||||
|
if not attachment_match[2]:
|
||||||
|
return 200, attachment
|
||||||
|
params = self.attachment_query(target.query)
|
||||||
|
variant = params.get("variant", ["original"])
|
||||||
|
if len(variant) != 1:
|
||||||
|
raise invalid("Invalid variant")
|
||||||
|
if attachment["status"] != "ready":
|
||||||
|
raise ApiError(409, "conflict", "Attachment is not ready")
|
||||||
|
if variant[0] != "original":
|
||||||
|
selected = next((v for v in attachment["variants"] if v["name"] == variant[0]), None)
|
||||||
|
if selected is None:
|
||||||
|
raise not_found()
|
||||||
|
result = self.server.attachments.s3.get_object(
|
||||||
|
Bucket=self.server.attachments.bucket,
|
||||||
|
Key=f"attachments/{attachment['id']}/{variant[0]}")
|
||||||
|
return 200, (result["Body"], selected)
|
||||||
|
return 200, (self.server.attachments.download(attachment), attachment)
|
||||||
|
if match:
|
||||||
|
chat_id = canonical_id(unquote(match[1]))
|
||||||
|
chat = app.chat(actor, chat_id)
|
||||||
|
if match[2] == "attachments" and method == "POST":
|
||||||
|
filenames = self.attachment_query(target.query).get("filename", [])
|
||||||
|
if len(filenames) != 1:
|
||||||
|
raise invalid("Filename required")
|
||||||
|
return 202, self.server.attachments.upload(self, actor, chat_id, filenames[0])
|
||||||
|
if match[2] == "messages":
|
||||||
|
if method == "POST":
|
||||||
|
body = self.read_json()
|
||||||
|
if not isinstance(body, dict) or "text" not in body or body.keys() - {"text", "attachment_ids"}:
|
||||||
|
raise invalid("Invalid request fields")
|
||||||
|
attachment_ids = body.get("attachment_ids", [])
|
||||||
|
if not isinstance(attachment_ids, list) or len(attachment_ids) > 10:
|
||||||
|
raise invalid("Invalid attachment IDs")
|
||||||
|
attachment_ids = [canonical_id(item) for item in attachment_ids]
|
||||||
|
if len(set(attachment_ids)) != len(attachment_ids):
|
||||||
|
raise invalid("Duplicate attachment IDs")
|
||||||
|
text = body["text"]
|
||||||
|
if text != "" or not attachment_ids:
|
||||||
|
text = require_text(text, 4000)
|
||||||
|
key = self.headers.get("Idempotency-Key", "")
|
||||||
|
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
|
||||||
|
raise invalid("Invalid Idempotency-Key")
|
||||||
|
return 201, app.send(actor, chat_id, text, key, attachment_ids)
|
||||||
|
if method == "GET":
|
||||||
|
return 200, app.message_page(chat_id, *page_query(target.query))
|
||||||
|
elif match[2] is None and method == "GET":
|
||||||
|
return 200, chat
|
||||||
|
raise not_found()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def attachment_query(query):
|
||||||
|
try:
|
||||||
|
return parse_qs(query, keep_blank_values=True, max_num_fields=16, errors="strict")
|
||||||
|
except ValueError:
|
||||||
|
raise invalid("Invalid query") from None
|
||||||
|
|
||||||
|
def basic_credentials(self):
|
||||||
|
if self.headers.get("Content-Length", "0") != "0" or self.headers.get("Transfer-Encoding"):
|
||||||
|
raise invalid("Login does not accept a body")
|
||||||
|
match = re.fullmatch(r"(?i:Basic) ([A-Za-z0-9+/=]{1,800})",
|
||||||
|
self.headers.get("Authorization", ""))
|
||||||
|
if not match:
|
||||||
|
raise unauthorized("Basic")
|
||||||
|
try:
|
||||||
|
value = base64.b64decode(match[1], validate=True).decode("utf-8")
|
||||||
|
except ValueError:
|
||||||
|
raise unauthorized("Basic") from None
|
||||||
|
username, separator, password = value.partition(":")
|
||||||
|
if not separator or not re.fullmatch(r"[a-z0-9_]{3,32}", username) or not 12 <= len(password) <= 128:
|
||||||
|
raise unauthorized("Basic")
|
||||||
|
return username, password
|
||||||
|
|
||||||
|
|
||||||
|
class Server(ThreadingHTTPServer):
|
||||||
|
timeout = 0.25
|
||||||
|
request_queue_size = 64
|
||||||
|
|
||||||
|
def __init__(self, address):
|
||||||
|
self.app = Store()
|
||||||
|
self.attachments = Attachments(self.app)
|
||||||
|
self.instance_id = uuid4().hex
|
||||||
|
from pathlib import Path
|
||||||
|
Path("/tmp/instance-id").write_text(self.instance_id)
|
||||||
|
self.stopping = False
|
||||||
|
self.active = 0
|
||||||
|
self.workers = threading.Condition()
|
||||||
|
super().__init__(address, Handler)
|
||||||
|
|
||||||
|
def get_request(self):
|
||||||
|
connection, address = super().get_request()
|
||||||
|
connection.settimeout(4)
|
||||||
|
return connection, address
|
||||||
|
|
||||||
|
def verify_request(self, request, client_address):
|
||||||
|
return not self.stopping
|
||||||
|
|
||||||
|
def process_request(self, request, client_address):
|
||||||
|
with self.workers:
|
||||||
|
self.active += 1
|
||||||
|
try:
|
||||||
|
super().process_request(request, client_address)
|
||||||
|
except Exception:
|
||||||
|
self.worker_done()
|
||||||
|
raise
|
||||||
|
|
||||||
|
def process_request_thread(self, request, client_address):
|
||||||
|
try:
|
||||||
|
super().process_request_thread(request, client_address)
|
||||||
|
finally:
|
||||||
|
self.worker_done()
|
||||||
|
|
||||||
|
def worker_done(self):
|
||||||
|
with self.workers:
|
||||||
|
self.active -= 1
|
||||||
|
self.workers.notify_all()
|
||||||
|
|
||||||
|
def handle_error(self, request, client_address):
|
||||||
|
LOG.error("HTTP connection handler failed")
|
||||||
|
|
||||||
|
def stop(self, signum, frame):
|
||||||
|
self.stopping = True
|
||||||
|
|
||||||
|
def run(self):
|
||||||
|
while not self.stopping:
|
||||||
|
self.handle_request()
|
||||||
|
self.server_close()
|
||||||
|
with self.workers:
|
||||||
|
self.workers.wait_for(lambda: self.active == 0, timeout=5)
|
||||||
|
self.app.close()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
configure("messenger-api")
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||||
|
host = os.getenv("APP_HOST", "0.0.0.0")
|
||||||
|
port = int(os.getenv("APP_PORT", "8080"))
|
||||||
|
environment = os.getenv("APP_ENV", "lab")
|
||||||
|
with Server((host, port)) as server:
|
||||||
|
signal.signal(signal.SIGTERM, server.stop)
|
||||||
|
signal.signal(signal.SIGINT, server.stop)
|
||||||
|
LOG.info("started host=%s port=%s env=%s", host, server.server_port, environment)
|
||||||
|
server.run()
|
||||||
|
LOG.info("stopped")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+294
@@ -0,0 +1,294 @@
|
|||||||
|
from argon2 import PasswordHasher, Type
|
||||||
|
from argon2.exceptions import VerificationError, InvalidHashError
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from telemetry import operation, observe_store
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime
|
||||||
|
from threading import BoundedSemaphore
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg_pool import ConnectionPool, PoolTimeout
|
||||||
|
|
||||||
|
from config import positive_int, secret
|
||||||
|
from profile_cache import ProfileCache
|
||||||
|
from validation import ApiError, invalid, not_found
|
||||||
|
|
||||||
|
USER = "id, username, display_name, created_at"
|
||||||
|
MESSAGE = "id, chat_id, sender_id, text, created_at, attachment_ids"
|
||||||
|
CHAT = """c.id, c.title, c.created_at,
|
||||||
|
ARRAY(SELECT user_id FROM members WHERE chat_id=c.id ORDER BY position) AS member_ids"""
|
||||||
|
DB_UNAVAILABLE = (psycopg.OperationalError, PoolTimeout, psycopg.errors.QueryCanceled,
|
||||||
|
psycopg.errors.LockNotAvailable)
|
||||||
|
LOG = logging.getLogger("messenger")
|
||||||
|
|
||||||
|
|
||||||
|
def json_value(value):
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||||
|
if isinstance(value, UUID):
|
||||||
|
return str(value)
|
||||||
|
raise TypeError(type(value).__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def unavailable():
|
||||||
|
return ApiError(503, "unavailable", "Dependency temporarily unavailable")
|
||||||
|
|
||||||
|
|
||||||
|
def unauthorized(scheme):
|
||||||
|
challenge = f'{scheme} realm="messenger"'
|
||||||
|
if scheme == "Basic":
|
||||||
|
challenge += ', charset="UTF-8"'
|
||||||
|
return ApiError(401, "unauthorized", "Invalid credentials", {"WWW-Authenticate": challenge})
|
||||||
|
|
||||||
|
|
||||||
|
class TracedPool(ConnectionPool):
|
||||||
|
@contextmanager
|
||||||
|
def connection(self, *args, **kwargs):
|
||||||
|
with operation("postgresql.transaction"):
|
||||||
|
with super().connection(*args, **kwargs) as connection:
|
||||||
|
yield connection
|
||||||
|
|
||||||
|
|
||||||
|
class Store:
|
||||||
|
def __init__(self):
|
||||||
|
self.pool = TracedPool(
|
||||||
|
secret("DATABASE_URL"), min_size=1, max_size=8, max_waiting=24, timeout=1.5,
|
||||||
|
kwargs={"row_factory": dict_row, "connect_timeout": 2,
|
||||||
|
"options": "-c statement_timeout=3000 -c lock_timeout=2000 -c timezone=UTC"},
|
||||||
|
open=True, check=ConnectionPool.check_connection,
|
||||||
|
)
|
||||||
|
observe_store(self)
|
||||||
|
self.cache = ProfileCache(secret("CACHE_URL"))
|
||||||
|
self.cursor_key = bytes.fromhex(secret("CURSOR_KEY"))
|
||||||
|
self.ttl = positive_int("SESSION_TTL_SECONDS", 3600)
|
||||||
|
self.idempotency_ttl = positive_int("IDEMPOTENCY_TTL_SECONDS", 86400)
|
||||||
|
self.hash_slots = BoundedSemaphore(2)
|
||||||
|
self.hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1, type=Type.ID)
|
||||||
|
self.dummy_hash = self.hasher.hash("dummy-password-no-account").encode()
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
self.cache.close()
|
||||||
|
self.pool.close()
|
||||||
|
|
||||||
|
def ready(self):
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
db.execute("SELECT 1 FROM users LIMIT 1")
|
||||||
|
|
||||||
|
def password_hash(self, password, salt):
|
||||||
|
if not self.hash_slots.acquire(timeout=0.5):
|
||||||
|
raise unavailable()
|
||||||
|
try:
|
||||||
|
return self.hasher.hash(password).encode()
|
||||||
|
finally:
|
||||||
|
self.hash_slots.release()
|
||||||
|
|
||||||
|
def register(self, username, name, password):
|
||||||
|
password_hash = self.password_hash(password, secrets.token_bytes(16))
|
||||||
|
try:
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
return db.execute(f"""
|
||||||
|
INSERT INTO users (username,display_name,password_hash) VALUES (%s,%s,%s)
|
||||||
|
RETURNING {USER}
|
||||||
|
""", (username, name, password_hash)).fetchone()
|
||||||
|
except psycopg.errors.UniqueViolation:
|
||||||
|
raise ApiError(409, "conflict", "Username already exists") from None
|
||||||
|
|
||||||
|
def login(self, username, password):
|
||||||
|
key = hashlib.sha256(username.encode("ascii")).digest()
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
limited = db.execute("""
|
||||||
|
INSERT INTO login_limits (key,count,window_start) VALUES (%s,1,clock_timestamp())
|
||||||
|
ON CONFLICT (key) DO UPDATE SET
|
||||||
|
count=CASE WHEN login_limits.window_start < now()-interval '60 seconds'
|
||||||
|
THEN 1 ELSE login_limits.count+1 END,
|
||||||
|
window_start=CASE WHEN login_limits.window_start < now()-interval '60 seconds'
|
||||||
|
THEN now() ELSE login_limits.window_start END
|
||||||
|
RETURNING count
|
||||||
|
""", (key,)).fetchone()
|
||||||
|
if limited["count"] > 10:
|
||||||
|
raise ApiError(429, "rate_limited", "Login rate limit exceeded", {"Retry-After": "60"})
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
row = db.execute(f"SELECT {USER},password_hash FROM users WHERE username=%s",
|
||||||
|
(username,)).fetchone()
|
||||||
|
stored = row.pop("password_hash") if row else self.dummy_hash
|
||||||
|
rehash = False
|
||||||
|
if stored.startswith(b"$argon2id$"):
|
||||||
|
try:
|
||||||
|
if not self.hash_slots.acquire(timeout=0.5):
|
||||||
|
raise unavailable()
|
||||||
|
try:
|
||||||
|
matches = self.hasher.verify(stored.decode(), password)
|
||||||
|
rehash = self.hasher.check_needs_rehash(stored.decode())
|
||||||
|
finally:
|
||||||
|
self.hash_slots.release()
|
||||||
|
except (VerificationError, InvalidHashError):
|
||||||
|
matches = False
|
||||||
|
else:
|
||||||
|
if not self.hash_slots.acquire(timeout=0.5):
|
||||||
|
raise unavailable()
|
||||||
|
try:
|
||||||
|
computed = stored[:16] + hashlib.scrypt(
|
||||||
|
password.encode(), salt=stored[:16], n=2**15, r=8, p=1,
|
||||||
|
maxmem=64*1024**2, dklen=32)
|
||||||
|
matches = hmac.compare_digest(computed, stored)
|
||||||
|
rehash = matches
|
||||||
|
finally:
|
||||||
|
self.hash_slots.release()
|
||||||
|
if not matches or row is None:
|
||||||
|
raise unauthorized("Basic")
|
||||||
|
if rehash:
|
||||||
|
replacement = self.password_hash(password, b"")
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
db.execute("UPDATE users SET password_hash=%s WHERE id=%s AND password_hash=%s",
|
||||||
|
(replacement, row["id"], stored))
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
digest = self.token_hash(token)
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
db.execute("DELETE FROM sessions WHERE expires_at <= now()")
|
||||||
|
session = db.execute("""
|
||||||
|
INSERT INTO sessions (token_hash,user_id,expires_at)
|
||||||
|
VALUES (%s,%s,clock_timestamp() + %s * interval '1 second')
|
||||||
|
RETURNING expires_at
|
||||||
|
""", (digest, row["id"], self.ttl)).fetchone()
|
||||||
|
return {"token": token, "token_type": "Bearer", **session, "user": row}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def token_hash(token):
|
||||||
|
return hashlib.sha256(token.encode("ascii")).digest()
|
||||||
|
|
||||||
|
def actor(self, digest):
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
row = db.execute("""
|
||||||
|
SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at > clock_timestamp()
|
||||||
|
""", (digest,)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise unauthorized("Bearer")
|
||||||
|
return row["user_id"]
|
||||||
|
|
||||||
|
def user(self, user_id):
|
||||||
|
key = f"user:v1:{user_id}"
|
||||||
|
value = self.cache.get(key)
|
||||||
|
if value is not None:
|
||||||
|
try:
|
||||||
|
return json.loads(value)
|
||||||
|
except ValueError:
|
||||||
|
LOG.info("invalid profile cache value")
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
user = db.execute(f"SELECT {USER} FROM users WHERE id=%s", (user_id,)).fetchone()
|
||||||
|
self.cache.set(key, json.dumps(user, default=json_value))
|
||||||
|
return user
|
||||||
|
|
||||||
|
def logout(self, digest):
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
removed = db.execute("""
|
||||||
|
DELETE FROM sessions WHERE token_hash=%s AND expires_at > clock_timestamp()
|
||||||
|
""", (digest,)).rowcount
|
||||||
|
if not removed:
|
||||||
|
raise unauthorized("Bearer")
|
||||||
|
|
||||||
|
def create_chat(self, title, members):
|
||||||
|
try:
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
chat = db.execute("INSERT INTO chats (title) VALUES (%s) RETURNING *",
|
||||||
|
(title,)).fetchone()
|
||||||
|
with db.cursor() as cursor:
|
||||||
|
cursor.executemany("INSERT INTO members (chat_id,user_id,position) VALUES (%s,%s,%s)",
|
||||||
|
[(chat["id"], member, index) for index, member in enumerate(members)])
|
||||||
|
return {**chat, "member_ids": members}
|
||||||
|
except psycopg.errors.ForeignKeyViolation:
|
||||||
|
raise invalid("Unknown member") from None
|
||||||
|
|
||||||
|
def chat(self, actor, chat_id):
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
row = db.execute(f"""
|
||||||
|
SELECT {CHAT} FROM members m JOIN chats c ON c.id=m.chat_id
|
||||||
|
WHERE m.user_id=%s AND c.id=%s
|
||||||
|
""", (actor, chat_id)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise not_found()
|
||||||
|
return row
|
||||||
|
|
||||||
|
def send(self, actor, chat_id, text, key, attachment_ids):
|
||||||
|
fingerprint = hashlib.sha256(text.encode("utf-8")).digest()
|
||||||
|
if attachment_ids:
|
||||||
|
payload = json.dumps([text, attachment_ids], default=json_value).encode("utf-8")
|
||||||
|
fingerprint = hashlib.sha256(b"\x00" + payload).digest()
|
||||||
|
identity = (actor, chat_id, key)
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
db.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s,0))",
|
||||||
|
(f"{actor}:{chat_id}:{key}",))
|
||||||
|
request = db.execute("""
|
||||||
|
SELECT fingerprint,message_id FROM message_requests
|
||||||
|
WHERE actor_id=%s AND chat_id=%s AND key=%s AND expires_at > clock_timestamp()
|
||||||
|
""", identity).fetchone()
|
||||||
|
if request is not None:
|
||||||
|
if not hmac.compare_digest(request["fingerprint"], fingerprint):
|
||||||
|
raise ApiError(409, "conflict", "Idempotency key already used for another body")
|
||||||
|
return db.execute(f"SELECT {MESSAGE} FROM messages WHERE id=%s",
|
||||||
|
(request["message_id"],)).fetchone()
|
||||||
|
if attachment_ids:
|
||||||
|
row = db.execute("""
|
||||||
|
SELECT count(*) AS found FROM attachments
|
||||||
|
WHERE id=ANY(%s) AND chat_id=%s AND status IN ('queued','processing','ready')
|
||||||
|
""", (attachment_ids, chat_id)).fetchone()
|
||||||
|
if row["found"] != len(attachment_ids):
|
||||||
|
raise not_found()
|
||||||
|
message = db.execute(f"""
|
||||||
|
INSERT INTO messages (chat_id,sender_id,text,attachment_ids)
|
||||||
|
VALUES (%s,%s,%s,%s) RETURNING {MESSAGE}
|
||||||
|
""", (chat_id, actor, text, attachment_ids)).fetchone()
|
||||||
|
db.execute("""
|
||||||
|
INSERT INTO message_requests (actor_id,chat_id,key,fingerprint,message_id,expires_at)
|
||||||
|
VALUES (%s,%s,%s,%s,%s,clock_timestamp() + %s * interval '1 second')
|
||||||
|
ON CONFLICT (actor_id,chat_id,key) DO UPDATE
|
||||||
|
SET fingerprint=excluded.fingerprint,message_id=excluded.message_id,expires_at=excluded.expires_at
|
||||||
|
""", (*identity, fingerprint, message["id"], self.idempotency_ttl))
|
||||||
|
return message
|
||||||
|
|
||||||
|
def chat_page(self, actor, limit, cursor):
|
||||||
|
return self.page(f"""SELECT {CHAT} FROM members m JOIN chats c ON c.id=m.chat_id
|
||||||
|
WHERE m.user_id=%s""", "c.", ("chats", actor), limit, cursor)
|
||||||
|
|
||||||
|
def message_page(self, chat_id, limit, cursor):
|
||||||
|
return self.page(f"SELECT {MESSAGE} FROM messages WHERE chat_id=%s",
|
||||||
|
"", ("messages", chat_id), limit, cursor)
|
||||||
|
|
||||||
|
def page(self, query, prefix, scope, limit, cursor):
|
||||||
|
columns = f"{prefix}created_at, {prefix}id"
|
||||||
|
params = [scope[1]]
|
||||||
|
if cursor is not None:
|
||||||
|
params.extend(self.decode_cursor(cursor, scope))
|
||||||
|
query += f" AND ({columns}) > (%s,%s)"
|
||||||
|
with self.pool.connection() as db:
|
||||||
|
rows = db.execute(f"{query} ORDER BY {columns} LIMIT %s", (*params, limit + 1)).fetchall()
|
||||||
|
items = rows[:limit]
|
||||||
|
next_cursor = self.encode_cursor(scope, items[-1]) if len(rows) > limit else None
|
||||||
|
return {"items": items, "next_cursor": next_cursor}
|
||||||
|
|
||||||
|
def encode_cursor(self, scope, row):
|
||||||
|
payload = json.dumps([scope, row["created_at"], row["id"]],
|
||||||
|
separators=(",", ":"), default=json_value).encode("ascii")
|
||||||
|
signature = hmac.digest(self.cursor_key, payload, "sha256")
|
||||||
|
return base64.urlsafe_b64encode(signature + payload).decode("ascii").rstrip("=")
|
||||||
|
|
||||||
|
def decode_cursor(self, cursor, scope):
|
||||||
|
try:
|
||||||
|
if not 1 <= len(cursor) <= 256 or not cursor.isascii():
|
||||||
|
raise ValueError
|
||||||
|
data = base64.b64decode(cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True)
|
||||||
|
signature, payload = data[:32], data[32:]
|
||||||
|
if not hmac.compare_digest(signature, hmac.digest(self.cursor_key, payload, "sha256")):
|
||||||
|
raise ValueError
|
||||||
|
saved_scope, timestamp, record = json.loads(payload)
|
||||||
|
if saved_scope != [scope[0], str(scope[1])]:
|
||||||
|
raise ValueError
|
||||||
|
return datetime.fromisoformat(timestamp), UUID(record)
|
||||||
|
except ValueError:
|
||||||
|
raise invalid("Invalid cursor") from None
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
import resource as system_resource
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
from opentelemetry import metrics, trace
|
||||||
|
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||||
|
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||||
|
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||||
|
from opentelemetry.sdk.resources import Resource
|
||||||
|
from opentelemetry.sdk.trace import TracerProvider
|
||||||
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||||
|
from opentelemetry.sdk.metrics import MeterProvider
|
||||||
|
from opentelemetry.metrics import Observation
|
||||||
|
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||||
|
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||||
|
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||||
|
|
||||||
|
tracer = trace.get_tracer("messenger")
|
||||||
|
meter = metrics.get_meter("messenger")
|
||||||
|
|
||||||
|
|
||||||
|
def configure(service):
|
||||||
|
logging.getLogger("messenger").setLevel(logging.INFO)
|
||||||
|
resource = Resource.create({
|
||||||
|
"service.name": service, "service.version": "1.0",
|
||||||
|
"service.instance.id": socket.gethostname(), "deployment.environment.name": "lab",
|
||||||
|
})
|
||||||
|
import requests
|
||||||
|
session = requests.Session()
|
||||||
|
session.verify = "/tls/ca.pem"
|
||||||
|
session.cert = ("/tls/cert.pem", "/tls/key.pem")
|
||||||
|
endpoint = "https://otel-collector:4319"
|
||||||
|
traces = TracerProvider(resource=resource)
|
||||||
|
traces.add_span_processor(BatchSpanProcessor(
|
||||||
|
OTLPSpanExporter(endpoint=endpoint+"/v1/traces", session=session, certificate_file="/tls/ca.pem", client_certificate_file="/tls/cert.pem", client_key_file="/tls/key.pem", timeout=2), max_queue_size=256, max_export_batch_size=64,
|
||||||
|
))
|
||||||
|
trace.set_tracer_provider(traces)
|
||||||
|
reader = PeriodicExportingMetricReader(OTLPMetricExporter(endpoint=endpoint+"/v1/metrics", session=session, certificate_file="/tls/ca.pem", client_certificate_file="/tls/cert.pem", client_key_file="/tls/key.pem", timeout=2), export_interval_millis=5000)
|
||||||
|
metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader]))
|
||||||
|
logs = LoggerProvider(resource=resource)
|
||||||
|
logs.add_log_record_processor(BatchLogRecordProcessor(
|
||||||
|
OTLPLogExporter(endpoint=endpoint+"/v1/logs", session=session, certificate_file="/tls/ca.pem", client_certificate_file="/tls/cert.pem", client_key_file="/tls/key.pem", timeout=2), max_queue_size=256, max_export_batch_size=64))
|
||||||
|
logging.getLogger("messenger").addHandler(LoggingHandler(logger_provider=logs))
|
||||||
|
meter.create_observable_gauge("process_memory", unit="By", callbacks=[
|
||||||
|
lambda options: [Observation(system_resource.getrusage(system_resource.RUSAGE_SELF).ru_maxrss * 1024)]
|
||||||
|
])
|
||||||
|
meter.create_observable_counter("process_cpu", unit="s", callbacks=[
|
||||||
|
lambda options: [Observation(time.process_time())]
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def operation(name, kind=trace.SpanKind.INTERNAL, context=None):
|
||||||
|
with tracer.start_as_current_span(name, kind=kind, context=context):
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def route_template(path):
|
||||||
|
path = path.split("?", 1)[0]
|
||||||
|
path = re.sub(r"/[0-9a-fA-F-]{36}(?=/|$)", "/{id}", path)
|
||||||
|
allowed = {
|
||||||
|
"/health/live", "/health/ready", "/api/v1/users", "/api/v1/users/me",
|
||||||
|
"/api/v1/chats", "/api/v1/chats/{id}", "/api/v1/chats/{id}/messages",
|
||||||
|
"/api/v1/chats/{id}/attachments", "/api/v1/attachments/{id}",
|
||||||
|
"/api/v1/attachments/{id}/content", "/api/v1/auth/sessions",
|
||||||
|
"/api/v1/auth/sessions/current",
|
||||||
|
}
|
||||||
|
return path if path in allowed else "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
http_count = meter.create_counter("http_requests")
|
||||||
|
http_duration = meter.create_histogram("http_duration", unit="s")
|
||||||
|
jobs_count = meter.create_counter("jobs_processed")
|
||||||
|
jobs_duration = meter.create_histogram("job_duration", unit="s")
|
||||||
|
ready_duration = meter.create_histogram("attachment_ready_duration", unit="s")
|
||||||
|
worker_busy = meter.create_up_down_counter("worker_busy")
|
||||||
|
|
||||||
|
|
||||||
|
def observe_store(store):
|
||||||
|
def pool_values(field):
|
||||||
|
return lambda options: [Observation(store.pool.get_stats().get(field, 0))]
|
||||||
|
meter.create_observable_gauge("db_pool_used", callbacks=[
|
||||||
|
lambda options: [Observation(
|
||||||
|
store.pool.get_stats().get("pool_size", 0) - store.pool.get_stats().get("pool_available", 0))]
|
||||||
|
])
|
||||||
|
meter.create_observable_gauge("db_pool_waiting", callbacks=[pool_values("requests_waiting")])
|
||||||
|
|
||||||
|
|
||||||
|
def observe_queue(store):
|
||||||
|
def sample(options):
|
||||||
|
try:
|
||||||
|
with store.pool.connection() as db:
|
||||||
|
row = db.execute("""
|
||||||
|
SELECT count(*) AS depth,coalesce(extract(epoch FROM
|
||||||
|
now()-min(a.created_at)),0)::float AS age
|
||||||
|
FROM jobs j JOIN attachments a ON a.id=j.attachment_id WHERE NOT j.finished
|
||||||
|
""").fetchone()
|
||||||
|
return [Observation(row["depth"], {"measurement": "depth"}),
|
||||||
|
Observation(row["age"], {"measurement": "oldest_seconds"})]
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
meter.create_observable_gauge("queue", callbacks=[sample])
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import json
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
import selectors
|
||||||
|
import socket
|
||||||
|
import socketserver
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
from threading import BoundedSemaphore, Thread
|
||||||
|
|
||||||
|
CONFIG = json.loads(Path(sys.argv[1]).read_text())
|
||||||
|
SLOTS = BoundedSemaphore(32)
|
||||||
|
|
||||||
|
|
||||||
|
class Bridge(socketserver.BaseRequestHandler):
|
||||||
|
def handle(self):
|
||||||
|
if not SLOTS.acquire(blocking=False):
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||||
|
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||||
|
context.load_cert_chain("/tls/cert.pem", "/tls/key.pem")
|
||||||
|
context.load_verify_locations("/tls/ca.pem")
|
||||||
|
if CONFIG["clients"]:
|
||||||
|
context.verify_mode = ssl.CERT_REQUIRED
|
||||||
|
self.request.settimeout(3)
|
||||||
|
with context.wrap_socket(self.request, server_side=True) as client:
|
||||||
|
identity = None
|
||||||
|
if CONFIG["clients"]:
|
||||||
|
peer = client.getpeercert()
|
||||||
|
names = {value for kind, value in peer.get("subjectAltName", ()) if kind == "DNS"}
|
||||||
|
allowed = names & CONFIG["clients"].keys()
|
||||||
|
if len(allowed) != 1:
|
||||||
|
print("bridge denied identity", flush=True)
|
||||||
|
return
|
||||||
|
identity = allowed.pop()
|
||||||
|
revoked = Path("/tls/revoked.json")
|
||||||
|
if revoked.exists() and peer["serialNumber"].lower() in json.loads(revoked.read_text()):
|
||||||
|
return
|
||||||
|
with socket.create_connection(("127.0.0.1", CONFIG["backend"]), timeout=3) as target:
|
||||||
|
client.settimeout(12)
|
||||||
|
target.settimeout(12)
|
||||||
|
first = client.recv(65536)
|
||||||
|
methods = CONFIG["clients"].get(identity, []) if identity else []
|
||||||
|
if methods:
|
||||||
|
while b"\r\n\r\n" not in first:
|
||||||
|
if len(first) > 65536:
|
||||||
|
return
|
||||||
|
chunk = client.recv(65536)
|
||||||
|
if not chunk:
|
||||||
|
return
|
||||||
|
first += chunk
|
||||||
|
request_line = first.split(b"\r\n", 1)[0].split(b" ")
|
||||||
|
if len(request_line) != 3 or request_line[0].decode("ascii", errors="replace") not in methods:
|
||||||
|
print("bridge denied method", flush=True)
|
||||||
|
return
|
||||||
|
prefix = CONFIG.get("write_prefixes", {}).get(identity)
|
||||||
|
if prefix and request_line[0] == b"PUT":
|
||||||
|
if not re.fullmatch(re.escape(prefix.encode()) + rb"[a-f0-9-]{36}", request_line[1]):
|
||||||
|
return
|
||||||
|
header, content = first.split(b"\r\n\r\n", 1)
|
||||||
|
header = re.sub(rb"(?im)^connection:[^\r\n]*\r?\n?", b"", header)
|
||||||
|
first = header + b"\r\nConnection: close\r\n\r\n" + content
|
||||||
|
target.sendall(first)
|
||||||
|
|
||||||
|
def upstream():
|
||||||
|
try:
|
||||||
|
while data := client.recv(65536):
|
||||||
|
target.sendall(data)
|
||||||
|
except (OSError, ssl.SSLError):
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
target.shutdown(socket.SHUT_WR)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
thread = Thread(target=upstream, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
try:
|
||||||
|
while data := target.recv(65536):
|
||||||
|
client.sendall(data)
|
||||||
|
except (OSError, ssl.SSLError):
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
client.shutdown(socket.SHUT_RDWR)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
thread.join(timeout=1)
|
||||||
|
except (OSError, ssl.SSLError) as error:
|
||||||
|
print("bridge transport error " + type(error).__name__, flush=True)
|
||||||
|
finally:
|
||||||
|
SLOTS.release()
|
||||||
|
|
||||||
|
|
||||||
|
class Server(socketserver.ThreadingTCPServer):
|
||||||
|
allow_reuse_address = True
|
||||||
|
daemon_threads = True
|
||||||
|
request_queue_size = 64
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
with Server(("0.0.0.0", CONFIG["listen"]), Bridge) as server:
|
||||||
|
server.serve_forever(poll_interval=0.25)
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import re
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
|
||||||
|
class ApiError(Exception):
|
||||||
|
def __init__(self, status, code, message, headers=None):
|
||||||
|
super().__init__(message)
|
||||||
|
self.status = status
|
||||||
|
self.code = code
|
||||||
|
self.headers = headers or {}
|
||||||
|
|
||||||
|
|
||||||
|
def invalid(message):
|
||||||
|
return ApiError(400, "invalid_request", message)
|
||||||
|
|
||||||
|
|
||||||
|
def not_found():
|
||||||
|
return ApiError(404, "not_found", "Resource not found")
|
||||||
|
|
||||||
|
|
||||||
|
def canonical_id(value):
|
||||||
|
if not isinstance(value, str) or not re.fullmatch(
|
||||||
|
r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", value
|
||||||
|
):
|
||||||
|
raise invalid("Invalid UUID")
|
||||||
|
return UUID(value)
|
||||||
|
|
||||||
|
|
||||||
|
def require_fields(body, *fields):
|
||||||
|
if not isinstance(body, dict) or body.keys() != set(fields):
|
||||||
|
raise invalid("Invalid request fields")
|
||||||
|
|
||||||
|
|
||||||
|
def require_text(value, maximum):
|
||||||
|
if (
|
||||||
|
not isinstance(value, str)
|
||||||
|
or not value.strip()
|
||||||
|
or len(value) > maximum
|
||||||
|
or "\x00" in value
|
||||||
|
or re.search(r"[\ud800-\udfff]", value)
|
||||||
|
):
|
||||||
|
raise invalid("Invalid text field")
|
||||||
|
return value
|
||||||
+165
@@ -0,0 +1,165 @@
|
|||||||
|
from telemetry import configure, operation, jobs_count, jobs_duration, ready_duration, worker_busy
|
||||||
|
from opentelemetry import trace
|
||||||
|
from opentelemetry.propagate import extract
|
||||||
|
from io import BytesIO
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import signal
|
||||||
|
import time
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from botocore.exceptions import BotoCoreError, ClientError
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
import redis
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
|
||||||
|
from attachments import Attachments
|
||||||
|
from config import positive_int, secret
|
||||||
|
from storage import Store
|
||||||
|
|
||||||
|
|
||||||
|
def variants(data):
|
||||||
|
with Image.open(BytesIO(data)) as source:
|
||||||
|
if source.width * source.height > 40000000:
|
||||||
|
raise ValueError("pixel limit")
|
||||||
|
source.load()
|
||||||
|
oriented = ImageOps.exif_transpose(source).convert("RGBA")
|
||||||
|
image = Image.new("RGB", oriented.size, "white")
|
||||||
|
image.paste(oriented, mask=oriented.getchannel("A"))
|
||||||
|
thumbnail = image.copy()
|
||||||
|
width, height = image.size
|
||||||
|
scale = min(1, 256 / width, 256 / height)
|
||||||
|
thumbnail = thumbnail.resize((max(1, int(width * scale)), max(1, int(height * scale))))
|
||||||
|
crop = ImageOps.fit(image, (128, 128), method=Image.Resampling.LANCZOS)
|
||||||
|
optimized = image.copy()
|
||||||
|
optimized.thumbnail((1280, 1280))
|
||||||
|
for name, output, format, mime in (
|
||||||
|
("thumbnail", thumbnail, "JPEG", "image/jpeg"),
|
||||||
|
("crop", crop, "JPEG", "image/jpeg"),
|
||||||
|
("optimized", optimized, "WEBP", "image/webp"),
|
||||||
|
):
|
||||||
|
stream = BytesIO()
|
||||||
|
output.save(stream, format, quality=85)
|
||||||
|
content = stream.getvalue()
|
||||||
|
yield content, {"name": name, "content_type": mime, "width": output.width,
|
||||||
|
"height": output.height, "size_bytes": len(content),
|
||||||
|
"sha256": hashlib.sha256(content).hexdigest()}
|
||||||
|
|
||||||
|
|
||||||
|
def process(store, objects, job_id):
|
||||||
|
timeout = positive_int("JOB_TIMEOUT_SECONDS", 60)
|
||||||
|
maximum = positive_int("JOB_MAX_ATTEMPTS", 5)
|
||||||
|
with store.pool.connection() as db:
|
||||||
|
job = db.execute("""
|
||||||
|
SELECT j.*,a.status FROM jobs j JOIN attachments a ON a.id=j.attachment_id
|
||||||
|
WHERE j.id=%s FOR UPDATE OF j
|
||||||
|
""", (job_id,)).fetchone()
|
||||||
|
if job is None or job["finished"]:
|
||||||
|
return "duplicate"
|
||||||
|
if job["lease_until"] is not None and job["lease_until"].timestamp() > time.time():
|
||||||
|
return "deferred"
|
||||||
|
if job["next_attempt"].timestamp() > time.time():
|
||||||
|
return "deferred"
|
||||||
|
if job["attempt"] >= maximum:
|
||||||
|
db.execute("UPDATE jobs SET finished=true WHERE id=%s", (job_id,))
|
||||||
|
db.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted' WHERE id=%s",
|
||||||
|
(job["attachment_id"],))
|
||||||
|
return "deferred"
|
||||||
|
db.execute("UPDATE jobs SET attempt=attempt+1,lease_until=now()+%s*interval '1 second' WHERE id=%s",
|
||||||
|
(timeout + 10, job_id))
|
||||||
|
db.execute("UPDATE attachments SET status='processing',updated_at=now() WHERE id=%s",
|
||||||
|
(job["attachment_id"],))
|
||||||
|
attachment_id = job["attachment_id"]
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
|
||||||
|
def expire(signum, frame):
|
||||||
|
raise TimeoutError
|
||||||
|
|
||||||
|
signal.signal(signal.SIGALRM, expire)
|
||||||
|
signal.alarm(timeout)
|
||||||
|
try:
|
||||||
|
with objects.s3.get_object(Bucket=objects.bucket, Key=f"staging/{attachment_id}")["Body"] as body:
|
||||||
|
data = body.read(10485761)
|
||||||
|
if len(data) > 10485760:
|
||||||
|
raise ValueError("byte limit")
|
||||||
|
metadata = []
|
||||||
|
objects.s3.put_object(Bucket=objects.bucket, Key=objects.key(attachment_id), Body=data)
|
||||||
|
for content, descriptor in variants(data):
|
||||||
|
if time.monotonic() > deadline:
|
||||||
|
raise TimeoutError
|
||||||
|
objects.s3.put_object(Bucket=objects.bucket,
|
||||||
|
Key=f"attachments/{attachment_id}/{descriptor['name']}",
|
||||||
|
Body=content, ContentType=descriptor["content_type"])
|
||||||
|
metadata.append(descriptor)
|
||||||
|
if os.getenv("CRASH_AFTER_OBJECTS") == "1":
|
||||||
|
os._exit(17)
|
||||||
|
with store.pool.connection() as db:
|
||||||
|
db.execute("UPDATE attachments SET status='ready',ready=true,variants=%s,error_code=NULL,updated_at=now() WHERE id=%s",
|
||||||
|
(Jsonb(metadata), attachment_id))
|
||||||
|
db.execute("UPDATE jobs SET finished=true,lease_until=NULL WHERE id=%s", (job_id,))
|
||||||
|
except (ValueError, OSError, TimeoutError, BotoCoreError, ClientError) as error:
|
||||||
|
permanent = isinstance(error, (ValueError, OSError)) and not isinstance(error, TimeoutError)
|
||||||
|
failed = permanent or job["attempt"] + 1 >= maximum
|
||||||
|
with store.pool.connection() as db:
|
||||||
|
db.execute("UPDATE attachments SET status=%s,error_code=%s,updated_at=now() WHERE id=%s",
|
||||||
|
("failed" if failed else "queued",
|
||||||
|
"invalid_image" if permanent else "processing_failed", attachment_id))
|
||||||
|
db.execute("""
|
||||||
|
UPDATE jobs SET finished=%s,lease_until=NULL,published_at=NULL,
|
||||||
|
next_attempt=now()+%s*interval '1 second' WHERE id=%s
|
||||||
|
""", (failed, min(30, 2 ** job["attempt"]) + random.random(), job_id))
|
||||||
|
finally:
|
||||||
|
signal.alarm(0)
|
||||||
|
with store.pool.connection() as db:
|
||||||
|
result = db.execute("SELECT ready,status,created_at FROM attachments WHERE id=%s", (attachment_id,)).fetchone()
|
||||||
|
ready = result["ready"]
|
||||||
|
if ready:
|
||||||
|
objects.s3.delete_object(Bucket=objects.bucket, Key=f"staging/{attachment_id}")
|
||||||
|
ready_duration.record(time.time() - result["created_at"].timestamp(), {"job_type": "attachment.process.v1"})
|
||||||
|
return result["status"]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
configure("messenger-worker")
|
||||||
|
store = Store()
|
||||||
|
objects = Attachments(store)
|
||||||
|
broker = redis.Redis.from_url(secret("BROKER_URL"), ssl_ca_certs="/tls/ca.pem", ssl_certfile="/tls/cert.pem", ssl_keyfile="/tls/key.pem", socket_timeout=3, decode_responses=True)
|
||||||
|
consumer = uuid4().hex
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
broker.xgroup_create("images", "workers", id="0", mkstream=True)
|
||||||
|
except redis.ResponseError as error:
|
||||||
|
if "BUSYGROUP" not in str(error):
|
||||||
|
raise
|
||||||
|
reclaimed = broker.xautoclaim("images", "workers", consumer, 80000, count=1)[1]
|
||||||
|
entries = reclaimed
|
||||||
|
if not entries:
|
||||||
|
streams = broker.xreadgroup("workers", consumer, {"images": ">"}, count=1, block=1000)
|
||||||
|
entries = streams[0][1] if streams else []
|
||||||
|
for message_id, fields in entries:
|
||||||
|
payload = json.loads(fields["payload"])
|
||||||
|
started = time.monotonic()
|
||||||
|
with operation("attachment.process", trace.SpanKind.CONSUMER, extract(payload)):
|
||||||
|
worker_busy.add(1)
|
||||||
|
try:
|
||||||
|
outcome = process(store, objects, payload["job_id"])
|
||||||
|
finally:
|
||||||
|
worker_busy.add(-1)
|
||||||
|
logging.getLogger("messenger").info("job outcome=%s", outcome)
|
||||||
|
attributes = {"job_type": "attachment.process.v1", "outcome": outcome}
|
||||||
|
jobs_count.add(1, attributes)
|
||||||
|
jobs_duration.record(time.monotonic() - started, attributes)
|
||||||
|
|
||||||
|
broker.xack("images", "workers", message_id)
|
||||||
|
broker.xdel("images", message_id)
|
||||||
|
except Exception:
|
||||||
|
logging.warning("worker dependency unavailable")
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import json
|
||||||
|
import resource
|
||||||
|
import statistics
|
||||||
|
import time
|
||||||
|
|
||||||
|
from argon2 import PasswordHasher, Type
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1, type=Type.ID)
|
||||||
|
samples = []
|
||||||
|
for _ in range(20):
|
||||||
|
started = time.perf_counter()
|
||||||
|
value = hasher.hash("Synthetic benchmark password")
|
||||||
|
hasher.verify(value, "Synthetic benchmark password")
|
||||||
|
samples.append(time.perf_counter() - started)
|
||||||
|
ordered = sorted(samples)
|
||||||
|
print(json.dumps({
|
||||||
|
"samples": len(samples), "operation": "hash_plus_verify", "memory_kib": 19456,
|
||||||
|
"time_cost": 2, "parallelism": 1,
|
||||||
|
"p50_seconds": round(statistics.median(samples), 4),
|
||||||
|
"p95_seconds": round(ordered[18], 4),
|
||||||
|
"peak_rss_bytes": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024,
|
||||||
|
"server_max_parallel_hashes": 2,
|
||||||
|
}))
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import base64
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import ssl
|
||||||
|
import time
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
context = ssl.create_default_context(cafile=str(ROOT / "secrets/operator/ca.pem"))
|
||||||
|
password = (ROOT / "secrets/grafana_password").read_text().strip()
|
||||||
|
auth = base64.b64encode(("admin:" + password).encode()).decode()
|
||||||
|
paths = {
|
||||||
|
"Prometheus": "/api/datasources/uid/prometheus/health",
|
||||||
|
"Loki": "/api/datasources/uid/loki/health",
|
||||||
|
"Tempo": "/api/datasources/proxy/uid/tempo/api/search",
|
||||||
|
}
|
||||||
|
for name, path in paths.items():
|
||||||
|
deadline = time.monotonic() + 90
|
||||||
|
while True:
|
||||||
|
request = Request("https://localhost:13007" + path,
|
||||||
|
headers={"Authorization": "Basic " + auth})
|
||||||
|
try:
|
||||||
|
with urlopen(request, context=context, timeout=15) as response:
|
||||||
|
result = json.load(response)
|
||||||
|
if name == "Tempo":
|
||||||
|
assert isinstance(result.get("traces"), list)
|
||||||
|
else:
|
||||||
|
assert result.get("status") == "OK"
|
||||||
|
print("PASS: Grafana queries " + name + " through verified mTLS", flush=True)
|
||||||
|
break
|
||||||
|
except (HTTPError, URLError, TimeoutError, AssertionError):
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
raise
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||||
|
from client import Client, check
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args):
|
||||||
|
subprocess.run(["docker", "compose", *args], check=True, timeout=90,
|
||||||
|
stdout=subprocess.DEVNULL)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
client = Client()
|
||||||
|
owner, member, _, chat = client.bootstrap()
|
||||||
|
compose("stop", "worker", "dispatcher")
|
||||||
|
attachment, original = client.attachment(owner, chat)
|
||||||
|
client.message(owner, chat, "", attachments=[attachment["id"]])
|
||||||
|
path = "/api/v1/attachments/" + attachment["id"]
|
||||||
|
client.call("GET", path + "/content", 409, actor=owner)
|
||||||
|
compose("restart", "api-a", "api-b", "broker")
|
||||||
|
compose("start", "dispatcher", "worker")
|
||||||
|
ready = client.wait_ready(member, attachment)
|
||||||
|
check(client.call("GET", path + "/content", actor=member)["bytes"] == original,
|
||||||
|
"original changed")
|
||||||
|
check({v["name"] for v in ready["variants"]} == {"thumbnail", "crop", "optimized"},
|
||||||
|
"missing variants")
|
||||||
|
for variant in ready["variants"]:
|
||||||
|
downloaded = client.call("GET", path + "/content?variant=" + variant["name"], actor=member)
|
||||||
|
import hashlib
|
||||||
|
check(hashlib.sha256(downloaded["bytes"]).hexdigest() == variant["sha256"], "variant checksum")
|
||||||
|
print("PASS: queued attachment survives API/broker restart, 3 variants ready")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||||
|
from client import Client, check
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args):
|
||||||
|
return subprocess.check_output(["docker", "compose", *args], text=True, timeout=90).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def recreate(service, setting):
|
||||||
|
env = dict(os.environ)
|
||||||
|
env.update(setting)
|
||||||
|
subprocess.run(["docker", "compose", "up", "-d", "--no-deps", "--force-recreate", service],
|
||||||
|
env=env, check=True, timeout=90, stdout=subprocess.DEVNULL)
|
||||||
|
|
||||||
|
|
||||||
|
def job_for(attachment):
|
||||||
|
code = f"""
|
||||||
|
from storage import Store
|
||||||
|
s = Store()
|
||||||
|
try:
|
||||||
|
with s.pool.connection() as db:
|
||||||
|
print(db.execute('SELECT id FROM jobs WHERE attachment_id=%s',
|
||||||
|
('{attachment["id"]}',)).fetchone()['id'])
|
||||||
|
finally:
|
||||||
|
s.close()
|
||||||
|
"""
|
||||||
|
return compose("exec", "-T", "-w", "/app/src", "api-a", "python", "-c", code)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c = Client()
|
||||||
|
actor, _, _, chat = c.bootstrap()
|
||||||
|
recreate("dispatcher", {"CRASH_BEFORE_PUBLISH": "1"})
|
||||||
|
attachment, _ = c.attachment(actor, chat)
|
||||||
|
try:
|
||||||
|
time.sleep(1)
|
||||||
|
check(compose("ps", "-q", "--status", "running", "dispatcher") == "", "dispatcher did not crash")
|
||||||
|
finally:
|
||||||
|
recreate("dispatcher", {})
|
||||||
|
c.wait_ready(actor, attachment)
|
||||||
|
print("PASS: COMMIT/publish crash recovered from outbox", flush=True)
|
||||||
|
|
||||||
|
recreate("worker", {"CRASH_AFTER_OBJECTS": "1"})
|
||||||
|
attachment, _ = c.attachment(actor, chat)
|
||||||
|
try:
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
while compose("ps", "-q", "--status", "running", "worker"):
|
||||||
|
check(time.monotonic() < deadline, "worker did not crash")
|
||||||
|
time.sleep(0.5)
|
||||||
|
finally:
|
||||||
|
recreate("worker", {})
|
||||||
|
time.sleep(72)
|
||||||
|
c.wait_ready(actor, attachment)
|
||||||
|
job_id = job_for(attachment)
|
||||||
|
payload = {"schema_version": 1, "job_id": job_id, "attachment_id": attachment["id"],
|
||||||
|
"pipeline_version": 1, "attempt": 1, "type": "attachment.process.v1",
|
||||||
|
"created_at": "2026-11-30T00:00:00Z"}
|
||||||
|
compose("exec", "-T", "broker", "redis-cli", "XADD", "images", "*", "payload", json.dumps(payload))
|
||||||
|
time.sleep(1)
|
||||||
|
ready = c.wait_ready(actor, attachment)
|
||||||
|
check(len(ready["variants"]) == 3, "duplicate variants")
|
||||||
|
print("PASS: crash after S3 effect, lease recovery and duplicate delivery", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||||
|
from client import Client, check
|
||||||
|
from check_recovery import compose, job_for
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c = Client()
|
||||||
|
actor, _, _, chat = c.bootstrap()
|
||||||
|
compose("stop", "worker")
|
||||||
|
attachment, _ = c.attachment(actor, chat)
|
||||||
|
job_id = job_for(attachment)
|
||||||
|
code = f"""
|
||||||
|
from storage import Store
|
||||||
|
s = Store()
|
||||||
|
try:
|
||||||
|
with s.pool.connection() as db:
|
||||||
|
db.execute('UPDATE attachments SET status=%s,error_code=%s WHERE id=%s',
|
||||||
|
('failed','processing_failed','{attachment["id"]}'))
|
||||||
|
db.execute('UPDATE jobs SET finished=true WHERE id=%s', ('{job_id}',))
|
||||||
|
finally:
|
||||||
|
s.close()
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
compose("exec", "-T", "-w", "/app/src", "api-a", "python", "-c", code)
|
||||||
|
compose("exec", "-T", "api-a", "python", "src/replay_job.py", job_id)
|
||||||
|
finally:
|
||||||
|
compose("start", "worker")
|
||||||
|
ready = c.wait_ready(actor, attachment)
|
||||||
|
check(ready["status"] == "ready", "replay failed")
|
||||||
|
print("PASS: explicit failed-job replay completes original attachment")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / "tests"))
|
||||||
|
sys.path.insert(0, str(ROOT / "scripts"))
|
||||||
|
from client import Client, Failure, check
|
||||||
|
import bao_operator
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args, input=None):
|
||||||
|
result = subprocess.run(["docker", "compose", *args], cwd=ROOT, input=input,
|
||||||
|
text=True, check=True, timeout=90,
|
||||||
|
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||||
|
return result.stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def ready(client):
|
||||||
|
deadline = time.monotonic() + 45
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
client.call("GET", "/health/ready", schema="Health")
|
||||||
|
return
|
||||||
|
except Failure:
|
||||||
|
check(time.monotonic() < deadline, "stack did not recover")
|
||||||
|
time.sleep(0.5)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
client = Client("https://localhost:18443", str(ROOT / "secrets/operator/ca.pem"))
|
||||||
|
actor = client.user("rotation")
|
||||||
|
old_url = json.loads((ROOT / "secrets/operator/kv-bootstrap.json").read_text())["api-a"]["DATABASE_URL"]
|
||||||
|
image = compose("images", "-q", "api-a")
|
||||||
|
subprocess.run([sys.executable, "scripts/rotate.py", "secret"], cwd=ROOT, check=True, timeout=90)
|
||||||
|
ready(client)
|
||||||
|
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||||
|
code = f"""
|
||||||
|
import psycopg
|
||||||
|
try:
|
||||||
|
connection=psycopg.connect({old_url!r},connect_timeout=3)
|
||||||
|
except psycopg.OperationalError as error:
|
||||||
|
assert "password authentication failed" in str(error)
|
||||||
|
print("PASS: old DB credential rejected on new connection")
|
||||||
|
else:
|
||||||
|
connection.close()
|
||||||
|
raise AssertionError("old DB credential accepted")
|
||||||
|
"""
|
||||||
|
print(compose("exec", "-T", "api-a", "python", "-", input=code), flush=True)
|
||||||
|
check(compose("images", "-q", "api-a") == image, "image changed during secret rotation")
|
||||||
|
|
||||||
|
subprocess.run([sys.executable, "scripts/rotate.py", "certificate"], cwd=ROOT, check=True, timeout=90)
|
||||||
|
ready(client)
|
||||||
|
code = """
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0,"/checks")
|
||||||
|
from check_security import exchange,denied,request
|
||||||
|
payload=b"POST /v1/traces HTTP/1.0\\r\\nHost: otel-collector\\r\\nContent-Length: 0\\r\\n\\r\\n"
|
||||||
|
denied(lambda: exchange("otel-collector",4319,"revoked-api-a",payload))
|
||||||
|
try:
|
||||||
|
request("https://openbao:8200/v1/auth/cert/login","revoked-api-a",{"name":"api-a"})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("revoked certificate authenticated to OpenBao")
|
||||||
|
print("PASS: revoked leaf rejected by Collector and OpenBao")
|
||||||
|
"""
|
||||||
|
print(compose("run", "--rm", "--no-deps", "-T", "security-check", "-", input=code), flush=True)
|
||||||
|
check(compose("images", "-q", "api-a") == image, "image changed during certificate rotation")
|
||||||
|
|
||||||
|
state = json.loads((ROOT / "secrets/operator/bao-init.json").read_text())
|
||||||
|
bao_operator.request("auth/cert/certs/api-a", {
|
||||||
|
"certificate": (ROOT / "secrets/operator/ca.pem").read_text(),
|
||||||
|
"allowed_dns_sans": ["api-a"], "token_policies": ["api-a"],
|
||||||
|
"token_ttl": 2, "token_max_ttl": 2,
|
||||||
|
}, state["root_token"])
|
||||||
|
try:
|
||||||
|
code = """
|
||||||
|
import sys,time
|
||||||
|
sys.path.insert(0,"/checks")
|
||||||
|
from check_security import credentials,request
|
||||||
|
from urllib.error import HTTPError
|
||||||
|
values,auth=credentials("api-a")
|
||||||
|
assert auth["lease_duration"]<=2
|
||||||
|
time.sleep(3)
|
||||||
|
try:
|
||||||
|
request("https://openbao:8200/v1/secret/data/api-a","api-a",token=auth["client_token"])
|
||||||
|
except HTTPError as error:
|
||||||
|
assert error.code==403
|
||||||
|
else:
|
||||||
|
raise AssertionError("expired service token accepted")
|
||||||
|
print("PASS: expired OpenBao service token rejected")
|
||||||
|
"""
|
||||||
|
print(compose("run", "--rm", "--no-deps", "-T", "security-check", "-", input=code), flush=True)
|
||||||
|
finally:
|
||||||
|
bao_operator.main()
|
||||||
|
bao_operator.request("sys/seal", {}, state["root_token"], "PUT")
|
||||||
|
try:
|
||||||
|
code = """
|
||||||
|
import sys
|
||||||
|
sys.path.insert(0,"/checks")
|
||||||
|
from check_security import request
|
||||||
|
from urllib.error import HTTPError
|
||||||
|
try:
|
||||||
|
request("https://openbao:8200/v1/auth/cert/login","api-a",{"name":"api-a"})
|
||||||
|
except HTTPError as error:
|
||||||
|
assert error.code==503
|
||||||
|
else:
|
||||||
|
raise AssertionError("sealed OpenBao issued credentials")
|
||||||
|
print("PASS: sealed OpenBao refuses service authentication")
|
||||||
|
"""
|
||||||
|
print(compose("run", "--rm", "--no-deps", "-T", "security-check", "-", input=code), flush=True)
|
||||||
|
finally:
|
||||||
|
bao_operator.main()
|
||||||
|
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||||
|
print("PASS: original session valid after credential/certificate rotation and unseal")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
from urllib.parse import urlencode
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
from botocore.config import Config
|
||||||
|
from botocore.exceptions import BotoCoreError, ClientError
|
||||||
|
import psycopg
|
||||||
|
import redis
|
||||||
|
|
||||||
|
sys.path.insert(0, "/tests")
|
||||||
|
from client import Client, check
|
||||||
|
|
||||||
|
CA = "/tls/ca.pem"
|
||||||
|
|
||||||
|
|
||||||
|
def tls_context(role=None):
|
||||||
|
context = ssl.create_default_context(cafile=CA)
|
||||||
|
if role:
|
||||||
|
context.load_cert_chain(f"/identities/{role}/cert.pem", f"/identities/{role}/key.pem")
|
||||||
|
return context
|
||||||
|
|
||||||
|
|
||||||
|
def request(url, role, data=None, token=None, method=None):
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
if token:
|
||||||
|
headers["X-Vault-Token"] = token
|
||||||
|
req = Request(url, data=json.dumps(data).encode() if data is not None else None,
|
||||||
|
headers=headers, method=method)
|
||||||
|
with urlopen(req, context=tls_context(role), timeout=5) as response:
|
||||||
|
return json.load(response) if response.status != 204 else {}
|
||||||
|
|
||||||
|
|
||||||
|
def credentials(role):
|
||||||
|
auth = request("https://openbao:8200/v1/auth/cert/login", role, {"name": role})["auth"]
|
||||||
|
values = request(f"https://openbao:8200/v1/secret/data/{role}", role,
|
||||||
|
token=auth["client_token"])["data"]["data"]
|
||||||
|
return values, auth
|
||||||
|
|
||||||
|
|
||||||
|
def exchange(host, port, role, data):
|
||||||
|
with socket.create_connection((host, port), timeout=4) as sock:
|
||||||
|
with tls_context(role).wrap_socket(sock, server_hostname=host) as secured:
|
||||||
|
secured.sendall(data)
|
||||||
|
return secured.recv(1024)
|
||||||
|
|
||||||
|
|
||||||
|
def denied(call):
|
||||||
|
try:
|
||||||
|
result = call()
|
||||||
|
except (OSError, URLError, BotoCoreError, ClientError, psycopg.Error, redis.RedisError):
|
||||||
|
return
|
||||||
|
check(not result, "unauthorized connection succeeded")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
client = Client("https://lb:8443", CA)
|
||||||
|
actor, _, outsider, chat = client.bootstrap()
|
||||||
|
attachment, _ = client.attachment(actor, chat)
|
||||||
|
client.wait_ready(actor, attachment)
|
||||||
|
client.call("GET", "/api/v1/attachments/" + attachment["id"], 404, actor=outsider)
|
||||||
|
client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": actor["id"]})
|
||||||
|
print("PASS: HTTPS API, asynchronous images and cross-user ACL", flush=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
urlopen("https://lb:8443/health/live", context=ssl.create_default_context(), timeout=5)
|
||||||
|
except URLError as error:
|
||||||
|
check(isinstance(error.reason, ssl.SSLCertVerificationError), "wrong CA test was not a trust failure")
|
||||||
|
else:
|
||||||
|
raise AssertionError("untrusted CA accepted")
|
||||||
|
try:
|
||||||
|
with socket.create_connection(("lb", 8443), timeout=5) as sock:
|
||||||
|
tls_context().wrap_socket(sock, server_hostname="wrong.invalid")
|
||||||
|
except ssl.SSLCertVerificationError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise AssertionError("wrong hostname accepted")
|
||||||
|
print("PASS: server CA and hostname verification", flush=True)
|
||||||
|
|
||||||
|
get = b"GET /health/ready HTTP/1.0\r\nHost: api-a\r\n\r\n"
|
||||||
|
for target in ("api-a", "api-b"):
|
||||||
|
check(b"200" in exchange(target, 8443, "lb", get), "valid LB identity failed")
|
||||||
|
for role in (None, "foreign", "untrusted", "expired"):
|
||||||
|
denied(lambda: exchange(target, 8443, role, get))
|
||||||
|
denied(lambda: socket.create_connection((target, 8080), timeout=2))
|
||||||
|
print("PASS: both API replicas require allowed LB certificate; plaintext bypass closed", flush=True)
|
||||||
|
|
||||||
|
worker, _ = credentials("worker")
|
||||||
|
dispatcher, _ = credentials("dispatcher")
|
||||||
|
for role, values in (("worker", worker), ("dispatcher", dispatcher)):
|
||||||
|
broker = redis.Redis.from_url(values["BROKER_URL"], ssl_ca_certs=CA,
|
||||||
|
ssl_certfile=f"/identities/{role}/cert.pem", ssl_keyfile=f"/identities/{role}/key.pem",
|
||||||
|
socket_timeout=3)
|
||||||
|
check(broker.ping(), "authorized broker identity failed")
|
||||||
|
if role == "worker":
|
||||||
|
denied(lambda: broker.xadd("images", {"payload": "forbidden"}))
|
||||||
|
else:
|
||||||
|
denied(lambda: broker.xread({"images": "0"}))
|
||||||
|
broker.close()
|
||||||
|
for role in (None, "foreign", "untrusted"):
|
||||||
|
denied(lambda: exchange("broker", 6380, role, b"*1\r\n$4\r\nPING\r\n"))
|
||||||
|
print("PASS: broker mTLS identity and separate producer/consumer ACL", flush=True)
|
||||||
|
|
||||||
|
payload = b"POST /v1/traces HTTP/1.0\r\nHost: otel-collector\r\nContent-Type: application/x-protobuf\r\nContent-Length: 0\r\n\r\n"
|
||||||
|
for role in ("api-a", "worker"):
|
||||||
|
check(b"200" in exchange("otel-collector", 4319, role, payload),
|
||||||
|
"authorized Collector ingest failed")
|
||||||
|
for role in (None, "foreign", "untrusted"):
|
||||||
|
denied(lambda: exchange("otel-collector", 4319, role, payload))
|
||||||
|
print("PASS: Collector requires allowed service identities", flush=True)
|
||||||
|
|
||||||
|
api, auth = credentials("api-a")
|
||||||
|
check(auth["lease_duration"] <= 120, "OpenBao token TTL too long")
|
||||||
|
for path in ("secret/data/worker", "sys/policies/acl"):
|
||||||
|
try:
|
||||||
|
request("https://openbao:8200/v1/" + path, "api-a", token=auth["client_token"])
|
||||||
|
except HTTPError as error:
|
||||||
|
check(error.code == 403, "expected policy denial")
|
||||||
|
else:
|
||||||
|
raise AssertionError("OpenBao policy leaked another service secret")
|
||||||
|
print("PASS: OpenBao scoped read, cross-service and policy access denied, token TTL bounded", flush=True)
|
||||||
|
|
||||||
|
with psycopg.connect(api["DATABASE_URL"], connect_timeout=3) as connection:
|
||||||
|
check(connection.execute("SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()").fetchone()[0],
|
||||||
|
"PostgreSQL connection is plaintext")
|
||||||
|
user = connection.execute("SELECT password_hash FROM users WHERE id=%s", (actor["id"],)).fetchone()[0]
|
||||||
|
check(user.startswith(b"$argon2id$"), "registration did not use Argon2id")
|
||||||
|
denied(lambda: psycopg.connect(api["DATABASE_URL"], sslmode="disable", connect_timeout=3))
|
||||||
|
with psycopg.connect(worker["DATABASE_URL"], connect_timeout=3) as connection:
|
||||||
|
try:
|
||||||
|
connection.execute("DELETE FROM users")
|
||||||
|
except psycopg.errors.InsufficientPrivilege:
|
||||||
|
connection.rollback()
|
||||||
|
else:
|
||||||
|
raise AssertionError("worker modified users")
|
||||||
|
print("PASS: PostgreSQL TLS, Argon2id and least-privilege worker role", flush=True)
|
||||||
|
password = actor["registration"]["password"]
|
||||||
|
salt = bytes(range(16))
|
||||||
|
legacy = salt + hashlib.scrypt(password.encode(),salt=salt,n=2**15,r=8,p=1,
|
||||||
|
maxmem=64*1024**2,dklen=32)
|
||||||
|
with psycopg.connect(api["DATABASE_URL"],connect_timeout=3) as connection:
|
||||||
|
connection.execute("UPDATE users SET password_hash=%s WHERE id=%s",(legacy,actor["id"]))
|
||||||
|
valid = base64.b64encode((actor["user"]["username"]+":"+password).encode()).decode()
|
||||||
|
client.call("POST","/api/v1/auth/sessions",201,headers={"Authorization":"Basic "+valid},schema="Session")
|
||||||
|
with psycopg.connect(api["DATABASE_URL"],connect_timeout=3) as connection:
|
||||||
|
stored = connection.execute("SELECT password_hash FROM users WHERE id=%s",(actor["id"],)).fetchone()[0]
|
||||||
|
check(stored.startswith(b"$argon2id$"),"legacy hash was not rehashed")
|
||||||
|
print("PASS: successful login upgrades legacy scrypt hash to Argon2id",flush=True)
|
||||||
|
|
||||||
|
s3 = boto3.client("s3", endpoint_url="https://s3:9002", region_name="us-east-1",
|
||||||
|
verify=CA, aws_access_key_id=api["S3_ACCESS_KEY_ID"],
|
||||||
|
aws_secret_access_key=api["S3_SECRET_ACCESS_KEY"],
|
||||||
|
config=Config(client_cert=("/identities/api-a/cert.pem","/identities/api-a/key.pem"),
|
||||||
|
retries={"total_max_attempts": 1}, connect_timeout=2,read_timeout=3,
|
||||||
|
request_checksum_calculation="when_required", s3={"addressing_style":"path"}))
|
||||||
|
denied(lambda: s3.put_object(Bucket="messenger-attachments", Key="attachments/forbidden-"+uuid4().hex, Body=b"x"))
|
||||||
|
print("PASS: API S3 identity cannot write final-object prefix", flush=True)
|
||||||
|
|
||||||
|
basic = base64.b64encode((actor["user"]["username"] + ":wrong-password").encode()).decode()
|
||||||
|
observed = set()
|
||||||
|
rate_limited = False
|
||||||
|
for _ in range(12):
|
||||||
|
result = client.call("POST", "/api/v1/auth/sessions", [401,429],
|
||||||
|
headers={"Authorization":"Basic " + basic})
|
||||||
|
observed.add(result["headers"]["X-Instance-Id"])
|
||||||
|
if result["status"] == 429:
|
||||||
|
rate_limited = True
|
||||||
|
check(result["headers"].get("Retry-After"), "missing Retry-After")
|
||||||
|
break
|
||||||
|
check(rate_limited and len(observed) >= 2, "shared login rate limit did not cover both replicas")
|
||||||
|
print("PASS: shared login limit across both replicas with 429/Retry-After", flush=True)
|
||||||
|
deadline = time.monotonic()+60
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
with urlopen("https://loki:3101/ready",context=tls_context("operator"),timeout=5) as response:
|
||||||
|
if response.status==200:
|
||||||
|
break
|
||||||
|
except (OSError,URLError):
|
||||||
|
pass
|
||||||
|
check(time.monotonic()<deadline,"Loki did not become ready")
|
||||||
|
time.sleep(1)
|
||||||
|
query = urlencode({"query":'{service_name=~"messenger-api|messenger-worker"}',"limit":1000})
|
||||||
|
logs = request("https://loki:3101/loki/api/v1/query_range?"+query,"operator")
|
||||||
|
check(logs["data"]["result"],"no application logs through TLS path")
|
||||||
|
serialized = json.dumps(logs)
|
||||||
|
check(actor["token"] not in serialized and password not in serialized,"secret found in telemetry")
|
||||||
|
metrics = request("https://prometheus:9091/api/v1/query?"+urlencode({"query":"http_requests_total"}),"operator")
|
||||||
|
check(metrics["data"]["result"],"no application metrics through TLS path")
|
||||||
|
print("PASS: TLS telemetry query succeeds and logs exclude test password/session token",flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user