From 280c5a330082b843b3179d55b8684222c6cdb313 Mon Sep 17 00:00:00 2001 From: kirillka222 Date: Sun, 6 Dec 2026 15:19:24 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=A0=207:=20=D0=B1=D0=B5=D0=B7=D0=BE?= =?UTF-8?q?=D0=BF=D0=B0=D1=81=D0=BD=D0=BE=D1=81=D1=82=D1=8C,=20mTLS=20?= =?UTF-8?q?=D0=B8=20OpenBao=20=D0=BD=D0=B0=20=D0=BE=D1=86=D0=B5=D0=BD?= =?UTF-8?q?=D0=BA=D1=83=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/pull_request_template.md | 53 +- Dockerfile | 25 + Makefile | 5 +- REPORT.md | 95 ++- alembic.ini | 117 +++ alembic/README | 1 + alembic/env.py | 97 +++ alembic/script.py.mako | 26 + .../versions/08fe661df060_create_tables.py | 30 + .../12043b148948_add_outbox_events.py | 35 + .../157ed8ce0e22_add_attachment_lease.py | 33 + .../1c0bb32fbe88_add_status_to_attachments.py | 28 + .../2a1b3c4d5e6f_add_thumbnail_fields.py | 23 + ...3fbed8a46_add_timestamps_to_attachments.py | 31 + ...f2c_add_owner_and_sha256_to_attachments.py | 35 + .../versions/b24373e3b620_create_tables.py | 67 ++ .../bc35c1b6b748_seed_explain_test_10k.py | 43 + ...7aaedac6_add_attachment_ids_to_messages.py | 30 + alembic/versions/e090e7a3e071_add_crop_key.py | 20 + .../ea4f73899364_add_attachments_table.py | 40 + .../f9b85be2b710_seed_load_test_data.py | 69 ++ alembic/versions/ffdfa8869ddc_add_webp_key.py | 20 + app/__init__.py | 0 app/bao.py | 47 ++ app/config.py | 25 + app/database.py | 17 + app/dependencies.py | 6 + app/exceptions.py | 37 + app/image_processor.py | 62 ++ app/load_test.py | 336 ++++++++ app/main.py | 121 +++ app/middleware.py | 11 + app/models/__init__.py | 0 app/models/attachment.py | 48 ++ app/models/base.py | 4 + app/models/chat.py | 35 + app/models/message.py | 36 + app/models/outbox.py | 33 + app/models/user.py | 24 + app/outbox_dispatcher.py | 139 ++++ app/pagination.py | 20 + app/redis_client.py | 12 + app/replay_failed.py | 91 +++ app/routers/__init__.py | 0 app/routers/attachments.py | 285 +++++++ app/routers/auth.py | 106 +++ app/routers/chats.py | 139 ++++ app/routers/health.py | 34 + app/routers/messages.py | 181 +++++ app/routers/users.py | 55 ++ app/security.py | 104 +++ app/serve_tls.py | 35 + app/storage.py | 23 + app/telemetry.py | 136 ++++ app/transport.py | 26 + app/worker.py | 750 ++++++++++++++++++ contracts/trust-matrix.md | 28 +- docker-compose.yml | 256 ++++++ evidence/lab7-grade3.txt | 77 ++ infra/grafana/dashboards/messenger.json | 191 +++++ .../provisioning/dashboards/dashboards.yml | 13 + .../provisioning/datasources/datasources.yml | 47 ++ infra/lab6-baseline.md | 3 + infra/loki/loki.yml | 38 + infra/openbao/README.md | 8 +- infra/openbao/server.hcl | 13 + infra/openbao/service-policy.hcl | 3 + infra/otel/collector.yaml | 61 ++ infra/prometheus/prometheus.yml | 25 + infra/security/database-grants.sql | 16 + infra/security/minio-init.sh | 18 + infra/security/pg_hba.conf | 3 + infra/security/postgres.sh | 9 + infra/security/rabbitmq-plugins.conf | 1 + infra/security/rabbitmq.conf | 10 + infra/security/redis.conf | 9 + infra/security/telemetry.nginx.conf | 84 ++ infra/tempo/tempo.yml | 28 + nginx/nginx.conf | 58 ++ requirements.txt | 18 + schemas/__init__.py | 0 schemas/chat.py | 14 + schemas/message.py | 6 + schemas/user.py | 7 + scripts/__init__.py | 0 scripts/bench_password.py | 23 + scripts/check_telemetry.py | 52 ++ scripts/failover-test.sh | 21 + scripts/lab7.py | 322 ++++++++ scripts/ram-experiment.py | 90 +++ scripts/reconcile.py | 147 ++++ scripts/restart.sh | 8 + scripts/rolling-load.sh | 12 + scripts/rolling-update.sh | 20 + scripts/stop-one.sh | 31 + scripts/test-stream-limit.py | 61 ++ scripts/verify_lab7.py | 72 ++ security/THREAT_MODEL.md | 22 +- tests/check_attachment_status.py | 29 + tests/grade3_api.py | 86 ++ tests/test_worker_retry.py | 72 ++ 101 files changed, 5950 insertions(+), 63 deletions(-) create mode 100644 Dockerfile create mode 100644 alembic.ini create mode 100644 alembic/README create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 alembic/versions/08fe661df060_create_tables.py create mode 100644 alembic/versions/12043b148948_add_outbox_events.py create mode 100644 alembic/versions/157ed8ce0e22_add_attachment_lease.py create mode 100644 alembic/versions/1c0bb32fbe88_add_status_to_attachments.py create mode 100644 alembic/versions/2a1b3c4d5e6f_add_thumbnail_fields.py create mode 100644 alembic/versions/8203fbed8a46_add_timestamps_to_attachments.py create mode 100644 alembic/versions/b0f31212df2c_add_owner_and_sha256_to_attachments.py create mode 100644 alembic/versions/b24373e3b620_create_tables.py create mode 100644 alembic/versions/bc35c1b6b748_seed_explain_test_10k.py create mode 100644 alembic/versions/d78a7aaedac6_add_attachment_ids_to_messages.py create mode 100644 alembic/versions/e090e7a3e071_add_crop_key.py create mode 100644 alembic/versions/ea4f73899364_add_attachments_table.py create mode 100644 alembic/versions/f9b85be2b710_seed_load_test_data.py create mode 100644 alembic/versions/ffdfa8869ddc_add_webp_key.py create mode 100644 app/__init__.py create mode 100644 app/bao.py create mode 100644 app/config.py create mode 100644 app/database.py create mode 100644 app/dependencies.py create mode 100644 app/exceptions.py create mode 100644 app/image_processor.py create mode 100644 app/load_test.py create mode 100644 app/main.py create mode 100644 app/middleware.py create mode 100644 app/models/__init__.py create mode 100644 app/models/attachment.py create mode 100644 app/models/base.py create mode 100644 app/models/chat.py create mode 100644 app/models/message.py create mode 100644 app/models/outbox.py create mode 100644 app/models/user.py create mode 100644 app/outbox_dispatcher.py create mode 100644 app/pagination.py create mode 100644 app/redis_client.py create mode 100644 app/replay_failed.py create mode 100644 app/routers/__init__.py create mode 100644 app/routers/attachments.py create mode 100644 app/routers/auth.py create mode 100644 app/routers/chats.py create mode 100644 app/routers/health.py create mode 100644 app/routers/messages.py create mode 100644 app/routers/users.py create mode 100644 app/security.py create mode 100644 app/serve_tls.py create mode 100644 app/storage.py create mode 100644 app/telemetry.py create mode 100644 app/transport.py create mode 100644 app/worker.py create mode 100644 docker-compose.yml create mode 100644 evidence/lab7-grade3.txt create mode 100644 infra/grafana/dashboards/messenger.json create mode 100644 infra/grafana/provisioning/dashboards/dashboards.yml create mode 100644 infra/grafana/provisioning/datasources/datasources.yml create mode 100644 infra/lab6-baseline.md create mode 100644 infra/loki/loki.yml create mode 100644 infra/openbao/server.hcl create mode 100644 infra/openbao/service-policy.hcl create mode 100644 infra/otel/collector.yaml create mode 100644 infra/prometheus/prometheus.yml create mode 100644 infra/security/database-grants.sql create mode 100644 infra/security/minio-init.sh create mode 100644 infra/security/pg_hba.conf create mode 100644 infra/security/postgres.sh create mode 100644 infra/security/rabbitmq-plugins.conf create mode 100644 infra/security/rabbitmq.conf create mode 100644 infra/security/redis.conf create mode 100644 infra/security/telemetry.nginx.conf create mode 100644 infra/tempo/tempo.yml create mode 100644 nginx/nginx.conf create mode 100644 requirements.txt create mode 100644 schemas/__init__.py create mode 100644 schemas/chat.py create mode 100644 schemas/message.py create mode 100644 schemas/user.py create mode 100644 scripts/__init__.py create mode 100644 scripts/bench_password.py create mode 100644 scripts/check_telemetry.py create mode 100755 scripts/failover-test.sh create mode 100644 scripts/lab7.py create mode 100644 scripts/ram-experiment.py create mode 100644 scripts/reconcile.py create mode 100755 scripts/restart.sh create mode 100755 scripts/rolling-load.sh create mode 100755 scripts/rolling-update.sh create mode 100755 scripts/stop-one.sh create mode 100644 scripts/test-stream-limit.py create mode 100644 scripts/verify_lab7.py create mode 100644 tests/check_attachment_status.py create mode 100644 tests/grade3_api.py create mode 100644 tests/test_worker_retry.py diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 8aef0ffd..ab2589dd 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,18 +1,43 @@ ## Лабораторная 7 -Автор / группа: TODO -Целевая оценка (3/4/5): TODO -Трек 5, если заявлен: TODO +**Автор и группа** — Кирилл Долда, БПИ2301 -Что реализовано и что перенесено: TODO -Команды запуска из чистого clone: TODO -Результаты проверок и ссылка на REPORT.md: TODO -Ограничения / известные ошибки: TODO -Источники и использование ИИ: TODO +**Целевая оценка** — 3 -- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. -- [ ] Контракт и публичные тесты не ослаблены. -- [ ] make check и make test выполнены; приложен реальный вывод. -- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. -- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. -- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. +### Что реализовано и перенесено + +Из lab6 перенесены API мессенджера, миграции, обработка вложений через RabbitMQ и worker, transactional outbox и стек наблюдаемости. В lab7 настроены HTTPS на Nginx, обязательный mTLS между Nginx и обеими репликами API, TLS к зависимостям и OpenBao с раздельными политиками для сервисов. Добавлены Argon2id, ограничение частоты входа и размера запроса, модель угроз и матрица доверия. + +### Запуск из чистого clone + +Нужны Docker с Compose v2, Python 3.9+, OpenSSL 3, `make` и `curl`. Из корня репозитория выполнить: + +```sh +python3 scripts/lab7.py up +curl -fsS --cacert secrets/lab7/ca/ca.crt --retry 20 --retry-all-errors --retry-delay 1 https://localhost:8443/health/ready +make check +make test +make test-security +docker compose run --rm --no-deps verify -m scripts.verify_lab7 +``` + +### Результаты проверок + +Прошли `make check`, `make validate`, публичный HTTPS smoke и проверка недоверенного CA. Обе реплики отклонили внутренние подключения без клиентского сертификата, с чужим CA и с неверной идентичностью. Проверены ограничения политик OpenBao, права на вложения, `429` с `Retry-After`, `413`, logout и истечение сессии. + +После перезапуска сохранились данные и действующая сессия. При отказе реплики в повторном прогоне прошло **118 записей без ошибок**. Инструкция и полный вывод — в [REPORT.md](https://gitea.privcloud.tech/kirill_dolda/mtusi2026lab7/src/branch/solution/bpi2301-dolda/REPORT.md) и [evidence/lab7-grade3.txt](https://gitea.privcloud.tech/kirill_dolda/mtusi2026lab7/src/branch/solution/bpi2301-dolda/evidence/lab7-grade3.txt). + +### Ограничения + +Стенд проверен на локальном Docker Desktop с синтетическими данными. Балансировщик и хранилища представлены одиночными экземплярами. При холодном запуске возможен краткий `502`. В отдельной проверке при остановке `app1` первый запрос готовности получил `504`, повторный — `200`. + +### Источники и использование ИИ + +Использованы задание и контракты курса, [документация MDN по TLS](https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Transport_Layer_Security) и документация OpenBao по [AppRole](https://openbao.org/docs/auth/approle/) и [политикам](https://openbao.org/docs/concepts/policies/). Codex использовался при реализации, подготовке и запуске проверок, оформлении отчёта. + +- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. +- [x] Контракт и публичные тесты не ослаблены. +- [x] `make check` и `make test` выполнены, вывод приложен. +- [x] Сценарии отказов и безопасности для уровня 3 воспроизведены. +- [x] Все секреты и приватные ключи находятся вне Git, отчёт не содержит токенов. +- [x] README задания сохранён, REPORT.md содержит инструкцию запуска этого решения. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..d5adab18 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM python:3.13-slim@sha256:168d3a5d10f2152f8e8d77b6843ac82c22a846cfefeef7afdf9aa630404e82a7 + +ENV PYTHONDONTWRITEBYTECODE=1 + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +RUN useradd --create-home --shell /bin/bash appuser + +COPY app/ app/ +COPY schemas/ schemas/ + +COPY alembic.ini . +COPY alembic/ alembic/ +RUN chown -R appuser:appuser /app/alembic +COPY scripts/ /app/scripts/ + +USER appuser + +EXPOSE 8443 + +CMD ["python", "-m", "app.serve_tls"] + diff --git a/Makefile b/Makefile index 5ad43ade..2f75cd1b 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,9 @@ PYTHON ?= python3 BASE_URL ?= https://localhost:8443 -CA_FILE ?= +LAB7_STATE ?= secrets/lab7 +ifneq ($(filter https://localhost:% https://127.0.0.1:%,$(BASE_URL)),) +CA_FILE ?= $(shell test -f "$(LAB7_STATE)/ca/ca.crt" && printf '%s' "$(LAB7_STATE)/ca/ca.crt") +endif ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) diff --git a/REPORT.md b/REPORT.md index 9801db45..301ab788 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,90 @@ # Отчёт — лабораторная 7 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор и группа — Кирилл Долда, БПИ2301. +- Целевая оценка — 3. +- Источники — задание lab7, контракты курса, [документация MDN по TLS](https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Transport_Layer_Security) и документация OpenBao по [AppRole](https://openbao.org/docs/auth/approle/) и [политикам](https://openbao.org/docs/concepts/policies/). ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker с Compose v2, Python 3.9+, OpenSSL 3, `make` и `curl`. В образе приложения используется Python 3.13. OpenBao закреплён на 2.4.4, Collector на 0.123.0, Prometheus на 3.2.1, Loki на 3.4.2, Tempo на 2.7.1, Grafana на 11.5.2. Для образов Nginx и хранилищ указаны digest в Compose. + +Из корня репозитория запустить: + +```sh +python3 scripts/lab7.py up +export CA_FILE="$PWD/secrets/lab7/ca/ca.crt" +curl -fsS --cacert "$CA_FILE" --retry 20 --retry-all-errors --retry-delay 1 https://localhost:8443/health/ready +make check +make test +make test-security +docker compose run --rm --no-deps verify -m scripts.verify_lab7 +python3 tests/grade3_api.py --ca-file "$CA_FILE" +python3 scripts/check_telemetry.py +``` + +Для локального HTTPS Makefile автоматически берёт CA из `secrets/lab7/ca/ca.crt` или из `$LAB7_STATE/ca/ca.crt`. Параметр `CA_FILE` позволяет явно выбрать другой сертификат. + +Bootstrap локально создаёт CA, сертификаты и пароли, запускает OpenBao, выполняет операторский init/unseal, настраивает AppRole и KV, создаёт приватный bucket, применяет миграции и SQL-права, затем запускает API и worker. Повторный запуск использует прежние локальные ключи и пароли и выдаёт новые SecretID. При восстановлении старого тома OpenBao нужны соответствующие ему доли разблокировки. Root-токен и доли хранятся в `secrets/lab7/operator/openbao.json` с правами 0600. Этот каталог доступен оператору на хосте и отсутствует в контейнерах. Публичный CA можно передавать клиентам. + +Доступны HTTPS API на `8443`, OpenBao на `8200` и Grafana на `3443`. Все три порта привязаны к loopback хоста. Имя пользователя Grafana — `admin`. Пароль лежит в локальном `secrets/lab7/grafana/admin/admin_password`. + +Для параллельного стенда экспортируйте отдельные `COMPOSE_PROJECT_NAME`, абсолютный `LAB7_STATE` и свободные `HTTPS_PORT`, `BAO_HOST_PORT`, `GRAFANA_HTTPS_PORT`. Приложение получает служебные подключения из OpenBao. `.env.example` описывает интерфейсы шаблона, локальные секреты генерирует bootstrap. + +Остановка с сохранением данных — `docker compose down`. Для последующего запуска используйте `python3 scripts/lab7.py up`. После отдельного рестарта OpenBao выполните `python3 scripts/lab7.py unseal`. Для намеренного удаления учебных данных выполните `docker compose down --volumes` и отдельно удалите локальный каталог соответствующего стенда. Удаление тома OpenBao уничтожает связь с сохранёнными долями разблокировки. + +Полная проверка OpenAPI использует `requirements-dev.txt`: + +```sh +python3 -m venv .venv +.venv/bin/python -m pip install -r requirements-dev.txt +make validate PYTHON=.venv/bin/python +``` ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Сохранены модель данных, Redis-сессии, S3, очередь обработки изображений и transactional outbox из lab6. Nginx принимает HTTPS. FastAPI на каждой реплике проверяет клиентский TLS-сертификат и URI SAN ingress до разбора HTTP. Nginx проверяет сертификат реплики по общему DNS SAN `api.internal`. Внешнего HTTP-входа и опубликованных портов FastAPI нет. -## Доказательства критериев +OpenBao использует зашифрованное файловое хранилище в именованном томе. У API, worker, outbox и миграций разные пути секретов и роли. Токен действует до пяти минут и отзывается сразу после чтения. PostgreSQL, Redis, S3 и RabbitMQ проверяются клиентами по CA и имени сервера. Для связей наблюдаемости работает TLS-шлюз с отдельными полномочиями ingest, записи, чтения и scrape. За шлюзом Collector, Loki, Tempo, Prometheus и Grafana используют один локальный транспортный контур, где штатные HTTP-listeners доступны только через loopback. Набор связей, порты и проверки приведены в [матрице доверия](contracts/trust-matrix.md). -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +API и worker запускаются под непривилегированным пользователем с `cap_drop: ALL`, `no-new-privileges`, лимитами 0,75 CPU и 512 MiB. У контейнеров нет privileged, host networking или Docker socket. Лабораторные сертификаты действуют 90 дней, CA — 365 дней, AppRole SecretID — 30 дней. Новые пароли хранятся в формате Argon2id со случайной солью. Старые bcrypt-хеши продолжают проверяться. При переходе со старого HTTP-стенда пользователи входят заново, поскольку формат ключей сессий Redis изменён. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +Вход ограничен Nginx по реальному адресу соединения до 2 запросов в секунду с burst 12. При превышении возвращается 429 с `Retry-After`. Максимальное тело запроса — 10 MiB. Для Argon2id установлены 19 MiB, t=2, p=1. В контейнере с тем же лимитом на Apple M3 Pro измерены 40 хеширований и 40 проверок. Хеширование p50 12,99 мс и p95 40,42 мс, проверка p50 12,17 мс и p95 40,12 мс. Это микробенчмарк одной операции, без HTTP и фонового профиля нагрузки. Два параллельных вызова на реплику выделяют около 38 MiB под память Argon2 и укладываются в лимит контейнера. Повторить измерение можно так: -## Эксперименты и отказы +```sh +docker compose exec -T app1 python -m app.bao python -m scripts.bench_password +``` -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +## Проверки и отказы -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +Вывод тестов сохранён в [evidence/lab7-grade3.txt](evidence/lab7-grade3.txt). При холодном запуске Nginx может на несколько секунд вернуть 502, пока реплики загружают секреты и становятся доступны. Команда ожидания готовности выше выполняет повторные запросы. -## Ограничения и следующие шаги +| Критерий | Команда или сценарий | Наблюдаемый результат | +| --- | --- | --- | +| Структура и контракт | `make check`, `make validate`, `docker compose config --quiet` | Все три проверки прошли | +| HTTPS, бизнес-API и logout | `make test CA_FILE="$CA_FILE"` | Публичный smoke lab7 прошёл. Включает оригинал и JPEG-миниатюру, доступ постороннего, подмену X-User-Id и logout | +| Внешний TLS | `make test-security`, `python3 tests/grade3_api.py --ca-file "$CA_FILE"` | Доверенный CA и имя localhost работают. Пустое хранилище доверия и чужое имя отвергнуты | +| Внутренний mTLS | `docker compose run --rm --no-deps verify -m scripts.verify_lab7` | На обеих репликах проходит только сертификат ingress. Без сертификата, с чужим CA и с чужим URI SAN от доверенного CA подключения отклонены | +| OpenBao | Тот же тест `scripts.verify_lab7` | API и worker читают свои пути. Чтение чужого пути и запись политики возвращают 403 | +| Вход, размер, ACL вложений | `python3 tests/grade3_api.py --ca-file "$CA_FILE"` | Получены 429 с Retry-After и 413. Вложение чужого чата отклонено | +| Истечение сессии | Отдельный стенд с `SESSION_TTL_SECONDS=8` и `tests/grade3_api.py --expiry-only` | Сессия сначала действует, затем запрос возвращает 401 | +| Обработка ошибок задачи | `python3 tests/test_worker_retry.py --ca-file "$CA_FILE"` | Тестовое вложение с отсутствующим объектом после повторов перешло в `failed` с кодом `s3_download_error` | +| Наблюдаемость | `python3 scripts/check_telemetry.py` после smoke | Через Grafana доступны 4 метрики Prometheus. Для API и worker найден соответствующий лог Loki и трасса Tempo. Неавторизованный ingest возвращает 401 | +| Перезапуск | `make test-persistence CA_FILE="$CA_FILE" ACTION_SCRIPT=scripts/restart.sh` | Сессия и подтверждённые данные сохранились. Hook останавливает ingress и процессы приложения, перезапускает PostgreSQL, Redis, S3, RabbitMQ и OpenBao, выполняет unseal и поднимает приложение | +| Отказ реплики | `make test-failover CA_FILE="$CA_FILE" ACTION_SCRIPT=scripts/stop-one.sh` | При двух репликах до отказа получена 121 подтверждённая запись, ошибок 0, первая успешная запись после остановки через 0,813 с на отдельном тестовом стенде | -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Повторный прогон из чистого состояния подтвердил 118 записей без ошибок при отключении реплики. В отдельном readiness-прогоне после отключения app1 первый запрос получил 504, повторный — 200. Проверка app2 вернула 200. Дополнительные проверки TLS хранилищ, ограниченных ролей, токенов OpenBao и контейнеров записаны в evidence. + +Тест лимита входа намеренно исчерпывает квоту по IP. Запускайте `tests/grade3_api.py` после других сценариев со входом или подождите 7 секунд перед следующим сценарием. + +Проверку expiry следует делать в отдельном Compose-проекте, чтобы укороченный срок не влиял на рабочий стенд. Экспортируйте его параметры, как описано выше, и выполните: + +```sh +export SESSION_TTL_SECONDS=8 +python3 scripts/lab7.py up +python3 tests/grade3_api.py --base-url "https://localhost:$HTTPS_PORT" \ + --ca-file "$LAB7_STATE/ca/ca.crt" --expiry-only +``` + +## Ограничения + +Проверки использовали локальный Docker Desktop и синтетические данные. Хранилища и балансировщик представлены одиночными экземплярами. Отдельно проверялись отказ одной реплики API и перезапуск с сохранением данных. diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 00000000..0e50bdb1 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,117 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +# Use forward slashes (/) also on windows to provide an os agnostic path +script_location = alembic + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python>=3.9 or backports.zoneinfo library. +# Any required deps can installed by adding `alembic[tz]` to the pip requirements +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to alembic/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +# version_path_separator = newline +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the exec runner, execute a binary +# hooks = ruff +# ruff.type = exec +# ruff.executable = %(here)s/.venv/bin/ruff +# ruff.options = --fix REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/alembic/README b/alembic/README new file mode 100644 index 00000000..98e4f9c4 --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 00000000..ed981a3e --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,97 @@ +from app.models.base import Base +from app.models.user import User + +from app.models.chat import Chat, ChatMember +from app.models.message import Message +from app.config import DATABASE_URL + +import os +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +from app.models.attachment import Attachment +from app.models.outbox import OutboxEvent + + + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config +config.set_main_option("sqlalchemy.url", DATABASE_URL.replace("+asyncpg", "+psycopg2").replace("%", "%%")) + + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +target_metadata = Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + connect_args=( + {"sslmode": "verify-full", "sslrootcert": os.environ["TLS_CA_FILE"]} + if os.getenv("TLS_CA_FILE") else {} + ), + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, target_metadata=target_metadata + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 00000000..fbc4b07d --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/alembic/versions/08fe661df060_create_tables.py b/alembic/versions/08fe661df060_create_tables.py new file mode 100644 index 00000000..51c3cf25 --- /dev/null +++ b/alembic/versions/08fe661df060_create_tables.py @@ -0,0 +1,30 @@ +"""create tables + +Revision ID: 08fe661df060 +Revises: bc35c1b6b748 +Create Date: 2026-10-31 11:52:26.342048 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '08fe661df060' +down_revision: Union[str, None] = 'bc35c1b6b748' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + pass + # ### end Alembic commands ### diff --git a/alembic/versions/12043b148948_add_outbox_events.py b/alembic/versions/12043b148948_add_outbox_events.py new file mode 100644 index 00000000..03694f8b --- /dev/null +++ b/alembic/versions/12043b148948_add_outbox_events.py @@ -0,0 +1,35 @@ +from alembic import op +import sqlalchemy as sa + +revision = "12043b148948" +down_revision = "ffdfa8869ddc" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "outbox_events", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("attachment_id", sa.Uuid(), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False + ), + sa.Column( + "published_at", + sa.DateTime(timezone=True), + nullable=True + ), + sa.ForeignKeyConstraint( + ["attachment_id"], + ["attachments.id"] + ), + sa.PrimaryKeyConstraint("id") + ) + + +def downgrade() -> None: + op.drop_table("outbox_events") \ No newline at end of file diff --git a/alembic/versions/157ed8ce0e22_add_attachment_lease.py b/alembic/versions/157ed8ce0e22_add_attachment_lease.py new file mode 100644 index 00000000..3769c009 --- /dev/null +++ b/alembic/versions/157ed8ce0e22_add_attachment_lease.py @@ -0,0 +1,33 @@ + +"""add attachment lease + +Revision ID: 157ed8ce0e22 +Revises: 12043b148948 +Create Date: 2026-11-20 13:07:19.055182 +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +revision: str = "157ed8ce0e22" +down_revision: Union[str, None] = "12043b148948" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.add_column( + "attachments", + sa.Column( + "lease_expires_at", + sa.DateTime(timezone=True), + nullable=True, + ), + ) + + +def downgrade() -> None: + op.drop_column("attachments", "lease_expires_at") diff --git a/alembic/versions/1c0bb32fbe88_add_status_to_attachments.py b/alembic/versions/1c0bb32fbe88_add_status_to_attachments.py new file mode 100644 index 00000000..df49b1c0 --- /dev/null +++ b/alembic/versions/1c0bb32fbe88_add_status_to_attachments.py @@ -0,0 +1,28 @@ +"""add status to attachments + +Revision ID: 1c0bb32fbe88 +Revises: 8203fbed8a46 +Create Date: 2026-11-17 15:38:59.622410 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '1c0bb32fbe88' +down_revision: Union[str, None] = '8203fbed8a46' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.add_column('attachments', sa.Column('status', sa.String(), server_default='queued', nullable=False)) + op.add_column('attachments', sa.Column('error_code', sa.String(), nullable=True)) + + +def downgrade() -> None: + op.drop_column('attachments', 'error_code') + op.drop_column('attachments', 'status') \ No newline at end of file diff --git a/alembic/versions/2a1b3c4d5e6f_add_thumbnail_fields.py b/alembic/versions/2a1b3c4d5e6f_add_thumbnail_fields.py new file mode 100644 index 00000000..20151c60 --- /dev/null +++ b/alembic/versions/2a1b3c4d5e6f_add_thumbnail_fields.py @@ -0,0 +1,23 @@ +from alembic import op +import sqlalchemy as sa + +revision = "2a1b3c4d5e6f" +down_revision = "1c0bb32fbe88" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column("attachments", sa.Column("thumbnail_key", sa.String(), nullable=True)) + op.add_column("attachments", sa.Column("thumbnail_sha256", sa.String(), nullable=True)) + op.add_column("attachments", sa.Column("thumbnail_size_bytes", sa.Integer(), nullable=True)) + op.add_column("attachments", sa.Column("thumbnail_width", sa.Integer(), nullable=True)) + op.add_column("attachments", sa.Column("thumbnail_height", sa.Integer(), nullable=True)) + + +def downgrade(): + op.drop_column("attachments", "thumbnail_height") + op.drop_column("attachments", "thumbnail_width") + op.drop_column("attachments", "thumbnail_size_bytes") + op.drop_column("attachments", "thumbnail_sha256") + op.drop_column("attachments", "thumbnail_key") \ No newline at end of file diff --git a/alembic/versions/8203fbed8a46_add_timestamps_to_attachments.py b/alembic/versions/8203fbed8a46_add_timestamps_to_attachments.py new file mode 100644 index 00000000..d7e3a2d7 --- /dev/null +++ b/alembic/versions/8203fbed8a46_add_timestamps_to_attachments.py @@ -0,0 +1,31 @@ +"""add timestamps to attachments + +Revision ID: 8203fbed8a46 +Revises: b0f31212df2c +Create Date: 2026-11-11 15:59:23.045039 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '8203fbed8a46' +down_revision: Union[str, None] = 'b0f31212df2c' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # Добавляем колонки created_at и updated_at + op.add_column('attachments', sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False)) + op.add_column('attachments', sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False)) + # УДАЛЕНО: op.alter_column('attachments', 'user_id', ...) - чтобы не упасть на старых записях + + +def downgrade() -> None: + op.drop_column('attachments', 'updated_at') + op.drop_column('attachments', 'created_at') + # УДАЛЕНО: op.alter_column('attachments', 'user_id', nullable=True) \ No newline at end of file diff --git a/alembic/versions/b0f31212df2c_add_owner_and_sha256_to_attachments.py b/alembic/versions/b0f31212df2c_add_owner_and_sha256_to_attachments.py new file mode 100644 index 00000000..c095702f --- /dev/null +++ b/alembic/versions/b0f31212df2c_add_owner_and_sha256_to_attachments.py @@ -0,0 +1,35 @@ +"""add owner and sha256 to attachments + +Revision ID: b0f31212df2c +Revises: d78a7aaedac6 +Create Date: 2026-11-11 15:39:07.391800 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'b0f31212df2c' +down_revision: Union[str, None] = 'd78a7aaedac6' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # 1. Добавляем user_id с nullable=True, чтобы не упасть на старых данных + op.add_column('attachments', sa.Column('user_id', sa.UUID(), nullable=True)) + + # 2. Добавляем sha256 + op.add_column('attachments', sa.Column('sha256', sa.String(), nullable=True)) + + # 3. Создаем внешний ключ + op.create_foreign_key(None, 'attachments', 'users', ['user_id'], ['id'], ondelete='CASCADE') + + +def downgrade() -> None: + op.drop_constraint(None, 'attachments', type_='foreignkey') + op.drop_column('attachments', 'sha256') + op.drop_column('attachments', 'user_id') \ No newline at end of file diff --git a/alembic/versions/b24373e3b620_create_tables.py b/alembic/versions/b24373e3b620_create_tables.py new file mode 100644 index 00000000..eac7789d --- /dev/null +++ b/alembic/versions/b24373e3b620_create_tables.py @@ -0,0 +1,67 @@ +"""create tables + +Revision ID: b24373e3b620 +Revises: +Create Date: 2026-10-24 06:54:22.471827 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'b24373e3b620' +down_revision: Union[str, None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('chats', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('title', sa.String(length=100), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('users', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('username', sa.String(length=32), nullable=False), + sa.Column('display_name', sa.String(length=100), nullable=False), + sa.Column('password_hash', sa.String(length=255), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True) + op.create_table('chat_members', + sa.Column('chat_id', sa.UUID(), nullable=False), + sa.Column('user_id', sa.UUID(), nullable=False), + sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('chat_id', 'user_id') + ) + op.create_table('messages', + sa.Column('id', sa.UUID(), nullable=False), + sa.Column('chat_id', sa.UUID(), nullable=False), + sa.Column('sender_id', sa.UUID(), nullable=False), + sa.Column('text', sa.Text(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False), + sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['sender_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + op.create_index('ix_messages_chat_created_id', 'messages', ['chat_id', 'created_at', 'id'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index('ix_messages_chat_created_id', table_name='messages') + op.drop_table('messages') + op.drop_table('chat_members') + op.drop_index(op.f('ix_users_username'), table_name='users') + op.drop_table('users') + op.drop_table('chats') + # ### end Alembic commands ### diff --git a/alembic/versions/bc35c1b6b748_seed_explain_test_10k.py b/alembic/versions/bc35c1b6b748_seed_explain_test_10k.py new file mode 100644 index 00000000..19897503 --- /dev/null +++ b/alembic/versions/bc35c1b6b748_seed_explain_test_10k.py @@ -0,0 +1,43 @@ +"""seed explain test 10k + +Revision ID: bc35c1b6b748 +Revises: f9b85be2b710 +Create Date: 2026-10-24 07:04:09.294404 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'bc35c1b6b748' +down_revision: Union[str, None] = 'f9b85be2b710' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.execute(""" + INSERT INTO users (id, username, display_name, password_hash, created_at) + VALUES ('11111111-1111-1111-1111-111111111111', 'explain_test', 'Test', 'hash', NOW()) + ON CONFLICT DO NOTHING; + """) + + op.execute(""" + INSERT INTO chats (id, title, created_at) + VALUES ('22222222-2222-2222-2222-222222222222', 'Explain Chat', NOW()) + ON CONFLICT DO NOTHING; + """) + + op.execute(""" + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + SELECT gen_random_uuid(), '22222222-2222-2222-2222-222222222222', '11111111-1111-1111-1111-111111111111', 'Message ' || i, NOW() - (i || ' minutes')::interval + FROM generate_series(1, 10000) AS i; + """) + +def downgrade() -> None: + op.execute("DELETE FROM messages WHERE chat_id = '22222222-2222-2222-2222-222222222222';") + op.execute("DELETE FROM chats WHERE id = '22222222-2222-2222-2222-222222222222';") + op.execute("DELETE FROM users WHERE id = '11111111-1111-1111-1111-111111111111';") \ No newline at end of file diff --git a/alembic/versions/d78a7aaedac6_add_attachment_ids_to_messages.py b/alembic/versions/d78a7aaedac6_add_attachment_ids_to_messages.py new file mode 100644 index 00000000..6e284653 --- /dev/null +++ b/alembic/versions/d78a7aaedac6_add_attachment_ids_to_messages.py @@ -0,0 +1,30 @@ +"""add attachment_ids to messages + +Revision ID: d78a7aaedac6 +Revises: ea4f73899364 +Create Date: 2026-11-11 15:16:50.773392 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'd78a7aaedac6' +down_revision: Union[str, None] = 'ea4f73899364' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.add_column('messages', sa.Column('attachment_ids', sa.JSON(), nullable=True)) + + op.execute("UPDATE messages SET attachment_ids = '[]'::json WHERE attachment_ids IS NULL") + + op.alter_column('messages', 'attachment_ids', nullable=False, server_default='[]') + + +def downgrade() -> None: + op.drop_column('messages', 'attachment_ids') \ No newline at end of file diff --git a/alembic/versions/e090e7a3e071_add_crop_key.py b/alembic/versions/e090e7a3e071_add_crop_key.py new file mode 100644 index 00000000..4371e058 --- /dev/null +++ b/alembic/versions/e090e7a3e071_add_crop_key.py @@ -0,0 +1,20 @@ + +from alembic import op +import sqlalchemy as sa + + +revision = "e090e7a3e071" +down_revision = "2a1b3c4d5e6f" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column( + "attachments", + sa.Column("crop_key", sa.String(), nullable=True) + ) + + +def downgrade() -> None: + op.drop_column("attachments", "crop_key") diff --git a/alembic/versions/ea4f73899364_add_attachments_table.py b/alembic/versions/ea4f73899364_add_attachments_table.py new file mode 100644 index 00000000..ffb86529 --- /dev/null +++ b/alembic/versions/ea4f73899364_add_attachments_table.py @@ -0,0 +1,40 @@ +"""add attachments table + +Revision ID: ea4f73899364 +Revises: 08fe661df060 +Create Date: 2026-11-11 14:37:24.096041 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'ea4f73899364' +down_revision: Union[str, None] = '08fe661df060' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('attachments', + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('object_key', sa.String(), nullable=False), + sa.Column('filename', sa.String(), nullable=False), + sa.Column('mime_type', sa.String(), nullable=False), + sa.Column('size_bytes', sa.Integer(), nullable=False), + sa.Column('chat_id', sa.UUID(), nullable=False), + sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('object_key') + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('attachments') + # ### end Alembic commands ### diff --git a/alembic/versions/f9b85be2b710_seed_load_test_data.py b/alembic/versions/f9b85be2b710_seed_load_test_data.py new file mode 100644 index 00000000..35e4be61 --- /dev/null +++ b/alembic/versions/f9b85be2b710_seed_load_test_data.py @@ -0,0 +1,69 @@ +"""seed load test data + +Revision ID: f9b85be2b710 +Revises: b24373e3b620 +Create Date: ... +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'f9b85be2b710' +down_revision: Union[str, None] = 'b24373e3b620' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.execute(""" + INSERT INTO users (id, username, display_name, password_hash, created_at) + VALUES ('55555555-5555-4555-8555-555555555555', 'load_test', 'Load', 'hash', NOW()) + ON CONFLICT DO NOTHING; + """) + + op.execute(""" + INSERT INTO chats (id, title, created_at) VALUES + ('66666666-6666-4666-8666-666666666666', 'Big Chat', NOW()), + ('77777777-7777-4777-8777-777777777777', 'Small Chat 1', NOW()), + ('88888888-8888-4888-8888-888888888888', 'Small Chat 2', NOW()) + ON CONFLICT DO NOTHING; + """) + + op.execute(""" + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + SELECT gen_random_uuid(), '66666666-6666-4666-8666-666666666666', '55555555-5555-4555-8555-555555555555', 'Big ' || i, NOW() - (i || ' minutes')::interval + FROM generate_series(1, 80000) AS i; + """) + + op.execute(""" + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + SELECT gen_random_uuid(), '77777777-7777-4777-8777-777777777777', '55555555-5555-4555-8555-555555555555', 'Small1 ' || i, NOW() - (i || ' minutes')::interval + FROM generate_series(1, 10000) AS i; + """) + + op.execute(""" + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + SELECT gen_random_uuid(), '88888888-8888-4888-8888-888888888888', '55555555-5555-4555-8555-555555555555', 'Small2 ' || i, NOW() - (i || ' minutes')::interval + FROM generate_series(1, 10000) AS i; + """) + + +def downgrade() -> None: + op.execute(""" + DELETE FROM messages WHERE chat_id IN ( + '66666666-6666-4666-8666-666666666666', + '77777777-7777-4777-8777-777777777777', + '88888888-8888-4888-8888-888888888888' + ); + """) + op.execute(""" + DELETE FROM chats WHERE id IN ( + '66666666-6666-4666-8666-666666666666', + '77777777-7777-4777-8777-777777777777', + '88888888-8888-4888-8888-888888888888' + ); + """) + op.execute("DELETE FROM users WHERE id = '55555555-5555-4555-8555-555555555555';") \ No newline at end of file diff --git a/alembic/versions/ffdfa8869ddc_add_webp_key.py b/alembic/versions/ffdfa8869ddc_add_webp_key.py new file mode 100644 index 00000000..439a9852 --- /dev/null +++ b/alembic/versions/ffdfa8869ddc_add_webp_key.py @@ -0,0 +1,20 @@ + +from alembic import op +import sqlalchemy as sa + + +revision = "ffdfa8869ddc" +down_revision = "e090e7a3e071" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column( + "attachments", + sa.Column("webp_key", sa.String(), nullable=True) + ) + + +def downgrade() -> None: + op.drop_column("attachments", "webp_key") diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/bao.py b/app/bao.py new file mode 100644 index 00000000..22464ec9 --- /dev/null +++ b/app/bao.py @@ -0,0 +1,47 @@ +"""Load only this service's settings from OpenBao before starting it.""" +import json +import os +from pathlib import Path +import ssl +import sys +import urllib.request + +CA_FILE = "/run/ca/ca.crt" + + +def request(address, path, *, context, data=None, token=None): + if not address.startswith("https://"): + raise ValueError("OpenBao requires HTTPS") + headers = {"Content-Type": "application/json"} + if token: + headers["X-Vault-Token"] = token + req = urllib.request.Request( + address + "/v1/" + path, + headers=headers, + data=json.dumps(data).encode() if data is not None else None, + ) + with urllib.request.urlopen(req, context=context, timeout=8) as response: + payload = response.read() + return json.loads(payload) if payload else None + + +def service_token(address, context, identity=Path("/run/identity")): + role = {name: (identity / name).read_text().strip() for name in ("role_id", "secret_id")} + return request(address, "auth/approle/login", context=context, data=role)["auth"]["client_token"] + + +def main(): + address = os.environ["BAO_ADDR"] + role = os.environ["BAO_ROLE"] + context = ssl.create_default_context(cafile=CA_FILE) + try: + token = service_token(address, context) + values = request(address, f"messenger/data/{role}", context=context, token=token)["data"]["data"] + request(address, "auth/token/revoke-self", context=context, data={}, token=token) + except (OSError, ValueError, KeyError) as error: + raise SystemExit(f"OpenBao bootstrap failed ({type(error).__name__})") from None + os.execvpe(sys.argv[1], sys.argv[1:], {**os.environ, **values}) + + +if __name__ == "__main__": + main() diff --git a/app/config.py b/app/config.py new file mode 100644 index 00000000..b08a81fc --- /dev/null +++ b/app/config.py @@ -0,0 +1,25 @@ +import os + +DATABASE_URL = os.environ["DATABASE_URL"] +REDIS_URL = os.getenv("REDIS_URL", "redis://redis:6379/0") +SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600")) + +CODE_MAP = { + 400: "invalid_request", + 401: "unauthorized", + 404: "not_found", + 409: "conflict", + 413: "payload_too_large", + 415: "unsupported_media_type", + 429: "rate_limited", + 503: "unavailable", + 500: "internal_error", +} + +S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://minio:9000") +S3_REGION = os.getenv("S3_REGION", "us-east-1") +S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments") +S3_ACCESS_KEY_ID = os.getenv("S3_ACCESS_KEY_ID") +S3_SECRET_ACCESS_KEY = os.getenv("S3_SECRET_ACCESS_KEY") +MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760")) +MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000")) diff --git a/app/database.py b/app/database.py new file mode 100644 index 00000000..525a397d --- /dev/null +++ b/app/database.py @@ -0,0 +1,17 @@ +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from app.config import DATABASE_URL +from app.transport import database_tls + +engine = create_async_engine( + DATABASE_URL, + pool_size=5, + max_overflow=10, + pool_timeout=30, + pool_recycle=1800, + echo=False, + hide_parameters=True, + connect_args=database_tls(), +) + +async_session_maker = async_sessionmaker(engine, expire_on_commit=False) \ No newline at end of file diff --git a/app/dependencies.py b/app/dependencies.py new file mode 100644 index 00000000..647232bc --- /dev/null +++ b/app/dependencies.py @@ -0,0 +1,6 @@ +from sqlalchemy.ext.asyncio import AsyncSession +from app.database import async_session_maker + +async def get_session(): + async with async_session_maker() as session: + yield session \ No newline at end of file diff --git a/app/exceptions.py b/app/exceptions.py new file mode 100644 index 00000000..0e6b18a2 --- /dev/null +++ b/app/exceptions.py @@ -0,0 +1,37 @@ +from fastapi import HTTPException, Request +from fastapi.responses import JSONResponse +from fastapi.exceptions import RequestValidationError +from app.config import CODE_MAP + + +def error_response(request: Request, status_code: int, code: str, message: str, extra_headers: dict = None): + request_id = getattr(request.state, "request_id", "unknown") + + + headers = {"X-Request-Id": request_id} + if extra_headers: + headers.update(extra_headers) + + return JSONResponse( + status_code=status_code, + content={ + "error": { + "code": code, + "message": message, + "request_id": request_id, + } + }, + headers=headers, + ) + + +async def http_exception_handler(request: Request, exc: HTTPException): + code = CODE_MAP.get(exc.status_code, "internal_error") + return error_response(request, exc.status_code, code, str(exc.detail), extra_headers=exc.headers) + + +async def validation_exception_handler(request: Request, exc: RequestValidationError): + return error_response(request, 400, "invalid_request", "Ошибка валидации данных") + +async def internal_error_handler(request: Request, exc: Exception): + return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера") \ No newline at end of file diff --git a/app/image_processor.py b/app/image_processor.py new file mode 100644 index 00000000..cc42d41a --- /dev/null +++ b/app/image_processor.py @@ -0,0 +1,62 @@ +import sys +from pathlib import Path + +from PIL import Image, ImageOps, UnidentifiedImageError + + +MAX_INPUT_PIXELS = 20_000_000 + + +def main(): + input_path = Path(sys.argv[1]) + output_dir = Path(sys.argv[2]) + + try: + with Image.open(input_path) as source: + if source.width * source.height > MAX_INPUT_PIXELS: + return 20 + + source.load() + img = source.convert("RGB") + + crop = ImageOps.fit( + img, + (128, 128), + method=Image.Resampling.LANCZOS, + centering=(0.5, 0.5) + ) + + crop.save( + output_dir / "crop.jpg", + format="JPEG", + quality=85 + ) + + img.save( + output_dir / "optimized.webp", + format="WEBP", + quality=80, + method=6 + ) + + img.thumbnail((256, 256)) + + img.save( + output_dir / "thumbnail.jpg", + format="JPEG", + quality=85 + ) + + except ( + UnidentifiedImageError, + OSError, + ValueError, + Image.DecompressionBombError, + ): + return 21 + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/app/load_test.py b/app/load_test.py new file mode 100644 index 00000000..b01d88a0 --- /dev/null +++ b/app/load_test.py @@ -0,0 +1,336 @@ +import argparse +import asyncio +import csv +import hashlib +import io +import statistics +import time +import uuid +from pathlib import Path + +from PIL import Image +from sqlalchemy import select + +from app.config import S3_BUCKET +from app.models.attachment import Attachment +from app.models.outbox import OutboxEvent +from app.outbox_dispatcher import session_maker +from app.worker import minio_client + + +IMAGE_SIZES = [512, 1024, 2048] + + +def make_image(size): + image = Image.effect_noise((size, size), 80).convert("RGB") + + buffer = io.BytesIO() + image.save(buffer, format="JPEG", quality=85) + + return buffer.getvalue() + + +def percentile(values, percent): + values = sorted(values) + + if not values: + return None + + position = (len(values) - 1) * percent / 100 + lower = int(position) + upper = min(lower + 1, len(values) - 1) + + return values[lower] + ( + values[upper] - values[lower] + ) * (position - lower) + + +async def get_source(): + async with session_maker() as session: + result = await session.execute( + select(Attachment) + .where(Attachment.status == "ready") + .order_by(Attachment.created_at.desc()) + .limit(1) + ) + + source = result.scalar_one_or_none() + + if source is None: + raise RuntimeError( + "Нет готовой фотографии для создания тестовых записей" + ) + + return source.chat_id, source.user_id + + +async def create_jobs(count_per_size, run_id): + chat_id, user_id = await get_source() + + jobs = [] + + for size in IMAGE_SIZES: + data = make_image(size) + + print( + f"[LOAD] Изображение {size}x{size}: " + f"{len(data) / 1024:.1f} KB", + flush=True, + ) + + for index in range(count_per_size): + key = f"benchmark/{run_id}/{size}_{index}.jpg" + + minio_client.put_object( + S3_BUCKET, + key, + io.BytesIO(data), + len(data), + content_type="image/jpeg", + ) + + jobs.append({ + "size": size, + "key": key, + "data": data, + }) + + async with session_maker() as session: + async with session.begin(): + for job in jobs: + data = job["data"] + + attachment = Attachment( + object_key=job["key"], + filename=f"benchmark_{job['size']}.jpg", + mime_type="image/jpeg", + size_bytes=len(data), + chat_id=chat_id, + user_id=user_id, + sha256=hashlib.sha256(data).hexdigest(), + status="queued", + ) + + session.add(attachment) + await session.flush() + + session.add( + OutboxEvent(attachment_id=attachment.id) + ) + + job["id"] = attachment.id + del job["data"] + + return jobs + + +async def monitor_jobs(jobs, timeout): + ids = [job["id"] for job in jobs] + + started = time.perf_counter() + last_report = started + + first_processing = {} + ready_times = {} + failed = set() + + peak_processing = 0 + + while True: + now = time.perf_counter() + elapsed = now - started + + async with session_maker() as session: + result = await session.execute( + select(Attachment.id, Attachment.status) + .where(Attachment.id.in_(ids)) + ) + + statuses = result.all() + + processing_count = 0 + + for attachment_id, status in statuses: + if status == "processing": + processing_count += 1 + + if attachment_id not in first_processing: + first_processing[attachment_id] = elapsed + + elif status == "ready": + if attachment_id not in ready_times: + ready_times[attachment_id] = elapsed + + elif status == "failed": + failed.add(attachment_id) + + peak_processing = max( + peak_processing, + processing_count, + ) + + completed = len(ready_times) + len(failed) + + if now - last_report >= 5: + print( + f"[LOAD] Готово: {len(ready_times)}/{len(jobs)}, " + f"failed={len(failed)}, " + f"processing={processing_count}, " + f"elapsed={elapsed:.1f}s", + flush=True, + ) + last_report = now + + if completed == len(jobs): + break + + if elapsed >= timeout: + print("[LOAD] Достигнут таймаут", flush=True) + break + + await asyncio.sleep(0.1) + + return { + "ready_times": ready_times, + "first_processing": first_processing, + "failed": failed, + "peak_processing": peak_processing, + "elapsed": time.perf_counter() - started, + } + + +def save_results(jobs, results, run_id): + output = Path(f"benchmark_{run_id}.csv") + + with output.open("w", newline="") as file: + writer = csv.writer(file) + + writer.writerow([ + "attachment_id", + "image_size", + "status", + "queue_lag_estimate_s", + "time_to_ready_s", + ]) + + for job in jobs: + attachment_id = job["id"] + + ready = results["ready_times"].get(attachment_id) + lag = results["first_processing"].get(attachment_id) + + status = ( + "ready" if ready is not None + else "failed" if attachment_id in results["failed"] + else "unfinished" + ) + + writer.writerow([ + str(attachment_id), + job["size"], + status, + round(lag, 3) if lag is not None else "", + round(ready, 3) if ready is not None else "", + ]) + + return output + + +def print_results(jobs, results): + ready_times = results["ready_times"] + first_processing = results["first_processing"] + + total = len(jobs) + completed = len(ready_times) + + throughput = ( + completed / results["elapsed"] + if results["elapsed"] > 0 + else 0 + ) + + print("\n========== BENCHMARK RESULTS ==========") + print(f"Total jobs: {total}") + print(f"Ready: {completed}") + print(f"Failed: {len(results['failed'])}") + print(f"Duration: {results['elapsed']:.2f} s") + print(f"Throughput: {throughput:.2f} images/s") + print(f"Peak observed processing: {results['peak_processing']}") + + for size in IMAGE_SIZES: + size_jobs = [ + job for job in jobs + if job["size"] == size + ] + + times = [ + ready_times[job["id"]] + for job in size_jobs + if job["id"] in ready_times + ] + + lags = [ + first_processing[job["id"]] + for job in size_jobs + if job["id"] in first_processing + ] + + print(f"\nImage size: {size}x{size}") + print(f"Completed: {len(times)}/{len(size_jobs)}") + + if times: + print(f"Mean ready: {statistics.mean(times):.2f} s") + print(f"P95 ready: {percentile(times, 95):.2f} s") + + if lags: + print(f"Mean observed queue lag: {statistics.mean(lags):.2f} s") + print(f"Queue lag samples: {len(lags)}/{len(size_jobs)}") + + print("\n=======================================") + + +async def main(): + parser = argparse.ArgumentParser() + + parser.add_argument( + "--count", + type=int, + default=10, + help="Количество изображений каждого размера", + ) + + parser.add_argument( + "--timeout", + type=int, + default=300, + ) + + args = parser.parse_args() + + if args.count < 1 or args.timeout < 1: + parser.error("--count и --timeout должны быть положительными") + + run_id = uuid.uuid4().hex[:8] + + print(f"[LOAD] Run ID: {run_id}") + print("[LOAD] Подготовка изображений...") + + jobs = await create_jobs(args.count, run_id) + + print(f"[LOAD] Создано заданий: {len(jobs)}") + print("[LOAD] Ожидание обработки...") + + results = await monitor_jobs(jobs, args.timeout) + + print_results(jobs, results) + + output = save_results(jobs, results, run_id) + + print(f"\nCSV: {output}") + + if len(results["ready_times"]) != len(jobs): + raise SystemExit(1) + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/app/main.py b/app/main.py new file mode 100644 index 00000000..9271b4b0 --- /dev/null +++ b/app/main.py @@ -0,0 +1,121 @@ +from fastapi import FastAPI +from fastapi.exceptions import RequestValidationError +from fastapi import HTTPException +import uuid +import time + +from opentelemetry.trace import SpanKind, Status, StatusCode + +from app.middleware import RequestIdMiddleware +from app.exceptions import http_exception_handler, validation_exception_handler +from app.routers import health, users, chats, messages, auth, attachments +from app.telemetry import setup_telemetry + + +app = FastAPI( + title="MTUSI Messenger", + version="1.1.0", +) + +tracer_provider, meter_provider, logger_provider, logger = setup_telemetry( + "messenger-api" +) + +tracer = tracer_provider.get_tracer(__name__) +meter = meter_provider.get_meter(__name__) + +http_requests = meter.create_counter( + name="http_requests", + description="Total HTTP requests", + unit="1", +) + +http_duration = meter.create_histogram( + name="http_request_duration", + description="HTTP request duration", + unit="s", +) + + +INSTANCE_ID = str(uuid.uuid4()) + + +@app.middleware("http") +async def add_instance_id_header(request, call_next): + response = await call_next(request) + response.headers["X-Instance-Id"] = INSTANCE_ID + return response + + +@app.middleware("http") +async def telemetry_middleware(request, call_next): + start_time = time.perf_counter() + method = request.method + status_code = 500 + + with tracer.start_as_current_span( + method, + kind=SpanKind.SERVER, + record_exception=False, + set_status_on_exception=False, + ) as span: + + try: + response = await call_next(request) + status_code = response.status_code + return response + + finally: + duration = time.perf_counter() - start_time + + route = request.scope.get("route") + route_template = getattr(route, "path", "unknown") + + attributes = { + "method": method, + "route": route_template, + "status_class": f"{status_code // 100}xx", + } + + http_requests.add(1, attributes) + http_duration.record(duration, attributes) + + span.update_name(f"{method} {route_template}") + span.set_attribute("http.request.method", method) + span.set_attribute("http.route", route_template) + span.set_attribute( + "http.response.status_code", + status_code, + ) + + if status_code >= 500: + span.set_status(Status(StatusCode.ERROR)) + + logger.log( + 40 if status_code >= 500 else 20, + "http_request_completed", + extra={ + "event": "http_request_completed", + "method": method, + "route": route_template, + "status_code": status_code, + "duration_seconds": duration, + "request_id": getattr( + request.state, + "request_id", + "", + ), + }, + ) + + +app.add_middleware(RequestIdMiddleware) +app.add_exception_handler(HTTPException, http_exception_handler) +app.add_exception_handler(RequestValidationError, validation_exception_handler) +app.include_router(health.router) +app.include_router(users.router) +app.include_router(chats.router) +app.include_router(messages.router) +app.include_router(auth.router) +app.include_router(attachments.router_upload) +app.include_router(attachments.router_download) \ No newline at end of file diff --git a/app/middleware.py b/app/middleware.py new file mode 100644 index 00000000..142c49e4 --- /dev/null +++ b/app/middleware.py @@ -0,0 +1,11 @@ +import uuid as uuid_lib +from starlette.middleware.base import BaseHTTPMiddleware + + +class RequestIdMiddleware(BaseHTTPMiddleware): + async def dispatch(self, request, call_next): + request_id = str(uuid_lib.uuid4()) + request.state.request_id = request_id + response = await call_next(request) + response.headers["X-Request-Id"] = request_id + return response \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/models/attachment.py b/app/models/attachment.py new file mode 100644 index 00000000..c5eeebef --- /dev/null +++ b/app/models/attachment.py @@ -0,0 +1,48 @@ + +import uuid +from datetime import datetime + +from sqlalchemy import String, Integer, ForeignKey, DateTime, func +from sqlalchemy.orm import Mapped, mapped_column + +from app.models.base import Base + + +class Attachment(Base): + __tablename__ = "attachments" + + id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4) + object_key: Mapped[str] = mapped_column(String, unique=True) + filename: Mapped[str] = mapped_column(String) + mime_type: Mapped[str] = mapped_column(String) + size_bytes: Mapped[int] = mapped_column(Integer) + chat_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("chats.id")) + user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE")) + sha256: Mapped[str] = mapped_column(String, nullable=True) + + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + server_default=func.now() + ) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + server_default=func.now(), + onupdate=func.now() + ) + + status: Mapped[str] = mapped_column(String, default="queued") + error_code: Mapped[str] = mapped_column(String, nullable=True) + + lease_expires_at: Mapped[datetime | None] = mapped_column( + DateTime(timezone=True), + nullable=True + ) + + thumbnail_key: Mapped[str] = mapped_column(String, nullable=True) + thumbnail_sha256: Mapped[str] = mapped_column(String, nullable=True) + thumbnail_size_bytes: Mapped[int] = mapped_column(Integer, nullable=True) + thumbnail_width: Mapped[int] = mapped_column(Integer, nullable=True) + thumbnail_height: Mapped[int] = mapped_column(Integer, nullable=True) + + crop_key: Mapped[str] = mapped_column(String, nullable=True) + webp_key: Mapped[str] = mapped_column(String, nullable=True) diff --git a/app/models/base.py b/app/models/base.py new file mode 100644 index 00000000..22784168 --- /dev/null +++ b/app/models/base.py @@ -0,0 +1,4 @@ +from sqlalchemy.orm import DeclarativeBase + +class Base(DeclarativeBase): + pass \ No newline at end of file diff --git a/app/models/chat.py b/app/models/chat.py new file mode 100644 index 00000000..7bfed508 --- /dev/null +++ b/app/models/chat.py @@ -0,0 +1,35 @@ +import uuid +from datetime import datetime + +from sqlalchemy import String, DateTime, ForeignKey, func +from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.dialects.postgresql import UUID + +from app.models.base import Base + + +class Chat(Base): + __tablename__ = "chats" + + id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), primary_key=True, default=uuid.uuid4 + ) + title: Mapped[str] = mapped_column(String(100), nullable=False) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now() + ) + + +class ChatMember(Base): + __tablename__ = "chat_members" + + chat_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("chats.id", ondelete="CASCADE"), + primary_key=True, + ) + user_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("users.id", ondelete="CASCADE"), + primary_key=True, + ) \ No newline at end of file diff --git a/app/models/message.py b/app/models/message.py new file mode 100644 index 00000000..291e5668 --- /dev/null +++ b/app/models/message.py @@ -0,0 +1,36 @@ +import uuid +from datetime import datetime + +from sqlalchemy import Text, DateTime, ForeignKey, Index, func, JSON +from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.dialects.postgresql import UUID + +from app.models.base import Base + + +class Message(Base): + __tablename__ = "messages" + + attachment_ids: Mapped[list] = mapped_column(JSON, default=list) + + id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), primary_key=True, default=uuid.uuid4 + ) + chat_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("chats.id", ondelete="CASCADE"), + nullable=False, + ) + sender_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("users.id", ondelete="CASCADE"), + nullable=False, + ) + text: Mapped[str] = mapped_column(Text, nullable=False) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now() + ) + + __table_args__ = ( + Index("ix_messages_chat_created_id", "chat_id", "created_at", "id"), + ) \ No newline at end of file diff --git a/app/models/outbox.py b/app/models/outbox.py new file mode 100644 index 00000000..a675b186 --- /dev/null +++ b/app/models/outbox.py @@ -0,0 +1,33 @@ +import uuid + +from datetime import datetime + +from sqlalchemy import DateTime, ForeignKey, func +from sqlalchemy.orm import Mapped, mapped_column + +from app.models.attachment import Base + + +class OutboxEvent(Base): + __tablename__ = "outbox_events" + + id: Mapped[uuid.UUID] = mapped_column( + primary_key=True, + default=uuid.uuid4 + ) + + attachment_id: Mapped[uuid.UUID] = mapped_column( + ForeignKey("attachments.id"), + nullable=False + ) + + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + server_default=func.now(), + nullable=False + ) + + published_at: Mapped[datetime | None] = mapped_column( + DateTime(timezone=True), + nullable=True + ) \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 00000000..03ab1ace --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,24 @@ +import uuid +from datetime import datetime + +from sqlalchemy import String, DateTime, func +from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.dialects.postgresql import UUID + +from app.models.base import Base + + +class User(Base): + __tablename__ = "users" + + id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), primary_key=True, default=uuid.uuid4 + ) + username: Mapped[str] = mapped_column( + String(32), unique=True, nullable=False, index=True + ) + display_name: Mapped[str] = mapped_column(String(100), nullable=False) + password_hash: Mapped[str] = mapped_column(String(255), nullable=False) + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), server_default=func.now() + ) \ No newline at end of file diff --git a/app/outbox_dispatcher.py b/app/outbox_dispatcher.py new file mode 100644 index 00000000..bb17d653 --- /dev/null +++ b/app/outbox_dispatcher.py @@ -0,0 +1,139 @@ + +import asyncio + +from app.transport import database_tls, service_tls +import json +import os +from datetime import datetime, timezone + +import aio_pika +from sqlalchemy import select +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from app.config import DATABASE_URL +from app.models.attachment import Attachment +from app.models.chat import Chat, ChatMember +from app.models.outbox import OutboxEvent +from app.models.user import User + +RABBITMQ_URL = os.environ["RABBITMQ_URL"] +QUEUE_NAME = "image_tasks" +POLL_INTERVAL_SECONDS = 1 + +engine = create_async_engine(DATABASE_URL, connect_args=database_tls(), hide_parameters=True) +session_maker = async_sessionmaker(engine, expire_on_commit=False) + + +async def recover_expired_lease(): + now = datetime.now(timezone.utc) + + async with session_maker() as session: + async with session.begin(): + result = await session.execute( + select(Attachment) + .where( + Attachment.status == "processing", + Attachment.lease_expires_at.is_not(None), + Attachment.lease_expires_at <= now, + ) + .order_by(Attachment.lease_expires_at) + .limit(1) + .with_for_update(skip_locked=True) + ) + + att = result.scalar_one_or_none() + + if att is None: + return False + + att.status = "queued" + att.lease_expires_at = None + + session.add( + OutboxEvent(attachment_id=att.id) + ) + + attachment_id = att.id + + print(f"[Outbox] Recovered expired lease: {attachment_id}", flush=True) + return True + + +async def dispatch_one(channel): + async with session_maker() as session: + async with session.begin(): + result = await session.execute( + select(OutboxEvent) + .where(OutboxEvent.published_at.is_(None)) + .order_by(OutboxEvent.created_at, OutboxEvent.id) + .limit(1) + .with_for_update(skip_locked=True) + ) + + event = result.scalar_one_or_none() + + if event is None: + return False + + confirmation = await channel.default_exchange.publish( + aio_pika.Message( + body=json.dumps( + {"attachment_id": str(event.attachment_id)} + ).encode(), + delivery_mode=aio_pika.DeliveryMode.PERSISTENT, + message_id=str(event.id), + content_type="application/json", + ), + routing_key=QUEUE_NAME, + mandatory=True, + ) + + if confirmation is False: + raise RuntimeError("RabbitMQ did not confirm publication") + + event.published_at = datetime.now(timezone.utc) + + print(f"[Outbox] Published {event.attachment_id}", flush=True) + return True + + +async def main(): + try: + while True: + try: + connection = await aio_pika.connect_robust(RABBITMQ_URL, ssl_context=service_tls()) + + async with connection: + channel = await connection.channel( + publisher_confirms=True, + on_return_raises=True, + ) + + await channel.declare_queue( + QUEUE_NAME, + durable=True, + ) + + while True: + recovered = await recover_expired_lease() + published = await dispatch_one(channel) + + if not recovered and not published: + await asyncio.sleep(POLL_INTERVAL_SECONDS) + + except asyncio.CancelledError: + raise + + except Exception as exc: + print( + f"[Outbox] Retry after error: {type(exc).__name__}", + flush=True, + ) + await asyncio.sleep(2) + + finally: + await engine.dispose() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/app/pagination.py b/app/pagination.py new file mode 100644 index 00000000..ca387009 --- /dev/null +++ b/app/pagination.py @@ -0,0 +1,20 @@ +def paginate(items: list, limit: int, cursor: str | None): + start = 0 + if cursor is not None: + try: + start = int(cursor) + except ValueError: + start = 0 + + if start < 0: + start = 0 + + page = items[start : start + limit] + next_index = start + limit + + if next_index < len(items): + next_cursor = str(next_index) + else: + next_cursor = None + + return page, next_cursor \ No newline at end of file diff --git a/app/redis_client.py b/app/redis_client.py new file mode 100644 index 00000000..c51b04d4 --- /dev/null +++ b/app/redis_client.py @@ -0,0 +1,12 @@ +import redis.asyncio as redis +import os +from app.config import REDIS_URL + +redis_client = redis.from_url( + REDIS_URL, + decode_responses=True, + socket_timeout=3, + socket_connect_timeout=3, + **({"ssl_ca_certs": os.environ["TLS_CA_FILE"], "ssl_check_hostname": True} + if REDIS_URL.startswith("rediss://") else {}), +) \ No newline at end of file diff --git a/app/replay_failed.py b/app/replay_failed.py new file mode 100644 index 00000000..2ba367fa --- /dev/null +++ b/app/replay_failed.py @@ -0,0 +1,91 @@ + +import asyncio +import sys +import uuid + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from app.config import DATABASE_URL +from app.models.attachment import Attachment +from app.models.outbox import OutboxEvent +from app.models.user import User +from app.models.chat import Chat, ChatMember + + +RETRYABLE_ERROR_CODES = { + "s3_download_error", + "s3_upload_error", + "image_processing_timeout", + "image_processor_start_error", + "image_processor_error", + "image_processor_output_error", + "worker_error", +} + + +async def replay_failed(attachment_id: uuid.UUID): + engine = create_async_engine(DATABASE_URL) + session_maker = async_sessionmaker(engine, expire_on_commit=False) + + try: + async with session_maker() as session: + async with session.begin(): + att = await session.get( + Attachment, + attachment_id, + with_for_update=True, + ) + + if att is None: + print("Файл не найден") + return + + if att.status != "failed": + print(f"Replay запрещён: status={att.status}") + return + + if att.error_code not in RETRYABLE_ERROR_CODES: + print( + f"Replay запрещён: error_code={att.error_code}" + ) + return + + pending = await session.scalar( + select(OutboxEvent.id) + .where( + OutboxEvent.attachment_id == attachment_id, + OutboxEvent.published_at.is_(None), + ) + .limit(1) + ) + + if pending is not None: + print("Задание уже ожидает публикации") + return + + att.status = "queued" + att.error_code = None + + session.add( + OutboxEvent(attachment_id=attachment_id) + ) + + print(f"Задание {attachment_id} отправлено на повторную обработку") + + finally: + await engine.dispose() + + +if __name__ == "__main__": + if len(sys.argv) != 2: + print("Использование: python -m app.replay_failed UUID") + sys.exit(1) + + try: + attachment_id = uuid.UUID(sys.argv[1]) + except ValueError: + print("Некорректный UUID") + sys.exit(1) + + asyncio.run(replay_failed(attachment_id)) diff --git a/app/routers/__init__.py b/app/routers/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/routers/attachments.py b/app/routers/attachments.py new file mode 100644 index 00000000..9472b468 --- /dev/null +++ b/app/routers/attachments.py @@ -0,0 +1,285 @@ +import uuid +import filetype +import io +import hashlib +from datetime import datetime, timezone +from PIL import Image +from fastapi import APIRouter, Depends, HTTPException, Query, Request +from fastapi.responses import StreamingResponse +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select, func, text + +from app.dependencies import get_session +from app.security import get_current_user +from app.models.user import User +from app.models.attachment import Attachment +from app.models.outbox import OutboxEvent +from app.models.chat import ChatMember +from app.storage import minio_client, BUCKET + + +router_upload = APIRouter( + prefix="/api/v1/chats/{chat_id}/attachments", + tags=["attachments"] +) + +router_download = APIRouter( + prefix="/api/v1/attachments", + tags=["attachments"] +) + +from app.config import MAX_UPLOAD_BYTES as MAX_SIZE, MAX_IMAGE_PIXELS as MAX_PIXELS +MAX_ACTIVE_ATTACHMENTS = 100 +ADMISSION_LOCK_KEY = 823164001 + +def format_utc_timestamp(value: datetime | None) -> str: + if value is None: + value = datetime.now(timezone.utc) + + elif value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + + return ( + value.astimezone(timezone.utc) + .isoformat() + .replace("+00:00", "Z") + ) + + +def build_attachment_response(att: Attachment) -> dict: + variants = [] + + if ( + att.status == "ready" + and att.thumbnail_key + and att.thumbnail_sha256 + and att.thumbnail_size_bytes is not None + and att.thumbnail_width is not None + and att.thumbnail_height is not None + ): + variants.append({ + "name": "thumbnail", + "content_type": "image/jpeg", + "size_bytes": att.thumbnail_size_bytes, + "width": att.thumbnail_width, + "height": att.thumbnail_height, + "sha256": att.thumbnail_sha256, + }) + + return { + "id": str(att.id), + "chat_id": str(att.chat_id), + "owner_id": str(att.user_id), + "filename": att.filename, + "content_type": att.mime_type, + "size_bytes": att.size_bytes, + "sha256": att.sha256, + "status": att.status, + "variants": variants, + "error_code": att.error_code, + "created_at": format_utc_timestamp(att.created_at), + "updated_at": format_utc_timestamp(att.updated_at), + } + + +@router_upload.post("", status_code=202) +async def upload_attachment( + chat_id: uuid.UUID, + filename: str = Query( + ..., + min_length=1, + max_length=255, + pattern=r"^[^/\\\x00]+$" + ), + request: Request = None, + user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_session), +): + result = await session.execute( + select(ChatMember).where( + ChatMember.chat_id == chat_id, + ChatMember.user_id == user.id, + ) + ) + + if not result.scalar_one_or_none(): + raise HTTPException(404, "Чат не найден") + + sha_hasher = hashlib.sha256() + buffer = io.BytesIO() + total = 0 + first_bytes = b"" + + async for chunk in request.stream(): + if not chunk: + continue + + total += len(chunk) + + if total > MAX_SIZE: + raise HTTPException(413, "File too large") + + sha_hasher.update(chunk) + buffer.write(chunk) + + if len(first_bytes) < 262: + need = 262 - len(first_bytes) + first_bytes += chunk[:need] + + kind = filetype.guess(first_bytes) + + if not kind or kind.mime not in ("image/png", "image/jpeg"): + raise HTTPException(400, "Only PNG/JPEG allowed") + + contents = buffer.getvalue() + + try: + img = Image.open(io.BytesIO(contents)) + + if img.width * img.height > MAX_PIXELS: + raise HTTPException(400, "Image too large (pixels)") + + except HTTPException: + raise + except Exception: + raise HTTPException(400, "Corrupted image") + + # Serialize admission checks across all API instances. + # This transaction-level PostgreSQL lock is released on commit/rollback. + await session.execute( + text("SELECT pg_advisory_xact_lock(:lock_key)"), + {"lock_key": ADMISSION_LOCK_KEY}, + ) + + active_count = await session.scalar( + select(func.count()) + .select_from(Attachment) + .where(Attachment.status.in_(("queued", "processing"))) + ) + + if active_count >= MAX_ACTIVE_ATTACHMENTS: + await session.rollback() + raise HTTPException( + status_code=429, + detail="Image processing queue is full; try again later", + headers={"Retry-After": "30"}, + ) + + object_key = f"originals/{uuid.uuid4()}.{kind.extension}" + + minio_client.put_object( + BUCKET, + object_key, + io.BytesIO(contents), + len(contents), + content_type=kind.mime, + ) + + sha_hash = sha_hasher.hexdigest() + + att = Attachment( + object_key=object_key, + filename=filename, + mime_type=kind.mime, + size_bytes=len(contents), + chat_id=chat_id, + user_id=user.id, + sha256=sha_hash, + status="queued" + ) + + session.add(att) + await session.flush() + + event = OutboxEvent(attachment_id=att.id) + session.add(event) + + await session.commit() + await session.refresh(att) + + return build_attachment_response(att) + + +@router_download.get("/{attachment_id}/content") +async def download_attachment_content( + attachment_id: uuid.UUID, + variant: str = "original", + user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_session), +): + att = await session.get(Attachment, attachment_id) + + if not att: + raise HTTPException(404, "Not found") + + result = await session.execute( + select(ChatMember).where( + ChatMember.chat_id == att.chat_id, + ChatMember.user_id == user.id, + ) + ) + + if not result.scalar_one_or_none(): + raise HTTPException(404, "Not found") + + if att.status != "ready": + raise HTTPException(409, "File is not ready yet") + + if variant == "thumbnail": + if not att.thumbnail_key: + raise HTTPException(404, "Thumbnail not found") + + key_to_download = att.thumbnail_key + mime = "image/jpeg" + + elif variant == "original": + key_to_download = att.object_key + mime = att.mime_type + + else: + raise HTTPException(404, "Variant not found") + + try: + response = minio_client.get_object( + BUCKET, + key_to_download + ) + + return StreamingResponse( + response, + media_type=mime, + headers={ + "Content-Disposition": + f'attachment; filename="{att.filename}"' + }, + ) + + except Exception: + raise HTTPException( + 404, + "File not found in storage" + ) + + +@router_download.get("/{attachment_id}") +async def get_attachment_metadata( + attachment_id: uuid.UUID, + user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_session), +): + att = await session.get(Attachment, attachment_id) + + if not att: + raise HTTPException(404, "Not found") + + result = await session.execute( + select(ChatMember).where( + ChatMember.chat_id == att.chat_id, + ChatMember.user_id == user.id, + ) + ) + + if not result.scalar_one_or_none(): + raise HTTPException(404, "Not found") + + return build_attachment_response(att) diff --git a/app/routers/auth.py b/app/routers/auth.py new file mode 100644 index 00000000..13e4691e --- /dev/null +++ b/app/routers/auth.py @@ -0,0 +1,106 @@ +from base64 import b64decode + +from fastapi import APIRouter, Depends, HTTPException, Request, status +from fastapi.security import HTTPBasic, HTTPBasicCredentials, HTTPAuthorizationCredentials +from fastapi.security.utils import get_authorization_scheme_param +from pydantic import BaseModel, ConfigDict, field_serializer +from app.redis_client import redis_client +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession +import uuid +from datetime import datetime + +from app.database import async_session_maker +from app.models.user import User +from app.security import check_password, create_session, delete_session, bearer_scheme, session_key + +router = APIRouter(prefix="/api/v1/auth", tags=["auth"]) +class Utf8Basic(HTTPBasic): + async def __call__(self, request: Request) -> HTTPBasicCredentials: + scheme, parameter = get_authorization_scheme_param(request.headers.get("Authorization")) + if scheme.lower() == "basic": + try: + username, separator, password = b64decode( + parameter, validate=True + ).decode("utf-8").partition(":") + if separator: + return HTTPBasicCredentials(username=username, password=password) + except ValueError: + pass + raise HTTPException( + status_code=401, + detail="Invalid Basic credentials", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + + +security = Utf8Basic(realm="messenger") + + +class UserResponse(BaseModel): + id: uuid.UUID + username: str + display_name: str + created_at: datetime + model_config = ConfigDict(from_attributes=True) + + @field_serializer('created_at') + def serialize_dt(self, dt: datetime): + return dt.isoformat().replace("+00:00", "Z") + + +class SessionResponse(BaseModel): + token: str + token_type: str + expires_at: str + user: UserResponse + + @field_serializer('expires_at') + def serialize_dt(self, dt_str: str): + if dt_str and dt_str.endswith("+00:00"): + return dt_str.replace("+00:00", "Z") + return dt_str + + +# Basic Auth в Bearer Token +@router.post("/sessions", status_code=201, response_model=SessionResponse) +async def login(credentials: HTTPBasicCredentials = Depends(security)): + async with async_session_maker() as session: + result = await session.execute(select(User).where(User.username == credentials.username)) + user = result.scalar_one_or_none() + + if not user or len(credentials.password) > 128 or not await check_password(credentials.password, user.password_hash): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + + session_data = await create_session(user.id) + + session_data["user"] = user + + return session_data + +@router.delete("/sessions/current", status_code=204) +async def logout(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)): + if not credentials: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Not authenticated", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + + token = credentials.credentials + + user_id = await redis_client.get(session_key(token)) + if not user_id: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid or expired token", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + + await delete_session(token) + return None + diff --git a/app/routers/chats.py b/app/routers/chats.py new file mode 100644 index 00000000..64299117 --- /dev/null +++ b/app/routers/chats.py @@ -0,0 +1,139 @@ +import uuid +from datetime import datetime +from fastapi import APIRouter, HTTPException, Depends +from pydantic import BaseModel, Field, field_validator, ConfigDict, field_serializer +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select + +from app.models.chat import Chat, ChatMember +from app.models.user import User +from app.security import get_current_user +from app.dependencies import get_session +from app.pagination import paginate + +router = APIRouter(prefix="/api/v1/chats", tags=["chats"]) + + +class CreateChat(BaseModel): + model_config = ConfigDict(extra="forbid") + title: str = Field(min_length=1, max_length=100) + member_ids: list[str] = Field(min_length=1, max_length=100) + + @field_validator("member_ids") + @classmethod + def unique_members(cls, v): + if len(set(v)) != len(v): + raise ValueError("member_ids должны быть уникальными") + return v + +class ChatResponse(BaseModel): + id: uuid.UUID + title: str + member_ids: list[uuid.UUID] + created_at: datetime + model_config = ConfigDict(from_attributes=True) + + @field_serializer('created_at') + def serialize_dt(self, dt: datetime): + return dt.isoformat().replace("+00:00", "Z") + + +@router.post("", status_code=201) +async def create_chat( + payload: CreateChat, + user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_session) +): + if str(user.id) not in payload.member_ids: + raise HTTPException(status_code=400, detail="Пользователь должен быть участником чата") + + for member_id in payload.member_ids: + result = await session.execute(select(User).where(User.id == member_id)) + if not result.scalar_one_or_none(): + raise HTTPException(status_code=400, detail=f"несуществующий пользователь: {member_id}") + + chat = Chat(title=payload.title) + session.add(chat) + await session.flush() + + for member_id in payload.member_ids: + session.add(ChatMember(chat_id=chat.id, user_id=member_id)) + + await session.commit() + await session.refresh(chat) + + return { + "id": chat.id, + "title": chat.title, + "member_ids": payload.member_ids, + "created_at": chat.created_at.isoformat().replace("+00:00", "Z"), + } + + +@router.get("/{chat_id}") +async def get_chat( + chat_id: str, + user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_session) +): + result = await session.execute(select(Chat).where(Chat.id == chat_id)) + chat = result.scalar_one_or_none() + + if not chat: + raise HTTPException(status_code=404, detail="чат не найден") + + result = await session.execute( + select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user.id) + ) + if not result.scalar_one_or_none(): + raise HTTPException(status_code=404, detail="чат не найден") + + result = await session.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat.id)) + member_ids = [] + for row in result.all(): + user_id = row[0] + member_ids.append(str(user_id)) + + return { + "id": chat.id, + "title": chat.title, + "member_ids": member_ids, + "created_at": chat.created_at.isoformat().replace("+00:00", "Z"), + } + + +@router.get("") +async def list_chats( + limit: int = 20, + cursor: str | None = None, + user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_session) +): + if limit < 1 or limit > 100: + raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100") + + result = await session.execute( + select(Chat) + .join(ChatMember, Chat.id == ChatMember.chat_id) + .where(ChatMember.user_id == user.id) + .order_by(Chat.created_at, Chat.id) + ) + chats = result.scalars().all() + + my_chats = [] + for chat in chats: + result = await session.execute(select(ChatMember.user_id).where(ChatMember.chat_id == chat.id)) + member_ids = [] + for row in result.all(): + user_id = row[0] + member_ids.append(str(user_id)) + + my_chats.append({ + "id": chat.id, + "title": chat.title, + "member_ids": member_ids, + "created_at": chat.created_at.isoformat().replace("+00:00", "Z"), + }) + + page, next_cursor = paginate(my_chats, limit, cursor) + return {"items": page, "next_cursor": next_cursor} \ No newline at end of file diff --git a/app/routers/health.py b/app/routers/health.py new file mode 100644 index 00000000..abcef176 --- /dev/null +++ b/app/routers/health.py @@ -0,0 +1,34 @@ +from fastapi import APIRouter +from fastapi import HTTPException +from sqlalchemy import text +from app.database import async_session_maker +from app.redis_client import redis_client + + +router = APIRouter(tags=["health"]) + + +@router.get("/health/live") +def live(): + return {"status": "ok"} + + +@router.get("/health/ready") +async def ready(): + try: + async with async_session_maker() as session: + await session.execute(text("SELECT 1")) + + await redis_client.ping() + + return {"status": "ok"} + except Exception: + raise HTTPException(status_code=503, detail="unavailable") + +@router.get("/") +def home(): + return { + "service": "MTUSI Messenger", + "version": "1.1.0", + "docs": "/docs", + } \ No newline at end of file diff --git a/app/routers/messages.py b/app/routers/messages.py new file mode 100644 index 00000000..baa2c11a --- /dev/null +++ b/app/routers/messages.py @@ -0,0 +1,181 @@ +import uuid +from datetime import datetime +from fastapi import APIRouter, HTTPException, Depends, Header +from pydantic import BaseModel, Field, ConfigDict, field_serializer, model_validator +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select +from app.redis_client import redis_client +import json + +from app.models.message import Message +from app.models.chat import Chat, ChatMember +from app.models.user import User +from app.models.attachment import Attachment +from app.security import get_current_user +from app.dependencies import get_session + +router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"]) + + +class CreateMessage(BaseModel): + model_config = ConfigDict(extra="forbid") + text: str = Field(min_length=0, max_length=4000) + attachment_ids: list[uuid.UUID] = [] + + @model_validator(mode="after") + def check_text_or_attachment(self): + if not self.text.strip() and not self.attachment_ids: + raise ValueError("Сообщение должно содержать текст или вложение") + return self + + +class MessageResponse(BaseModel): + id: uuid.UUID + chat_id: uuid.UUID + sender_id: uuid.UUID + text: str + created_at: datetime + model_config = ConfigDict(from_attributes=True) + attachment_ids: list[uuid.UUID] = [] + + @field_serializer('created_at') + def serialize_dt(self, dt: datetime): + return dt.isoformat().replace("+00:00", "Z") + + +async def check_chat_access(chat_id: str, user_id: uuid.UUID, session: AsyncSession): + chat = await session.get(Chat, chat_id) + if not chat: + raise HTTPException(status_code=404, detail="чат не найден") + + result = await session.execute( + select(ChatMember).where(ChatMember.chat_id == chat.id, ChatMember.user_id == user_id) + ) + if not result.scalar_one_or_none(): + raise HTTPException(status_code=404, detail="чат не найден") + return chat + + +@router.post("", status_code=201, response_model=MessageResponse) +async def create_message( + chat_id: str, + payload: CreateMessage, + idempotency_key: str = Header( + ..., + alias="Idempotency-Key", + min_length=1, + max_length=128, + pattern=r"^[A-Za-z0-9._:-]+$", + ), + user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_session) +): + await check_chat_access(chat_id, user.id, session) + + if payload.attachment_ids: + result = await session.execute( + select(Attachment.id).where( + Attachment.id.in_(payload.attachment_ids), + Attachment.chat_id == chat_id, + ) + ) + found_ids = {str(row[0]) for row in result.all()} + requested_ids = {str(a) for a in payload.attachment_ids} + if found_ids != requested_ids: + raise HTTPException( + status_code=400, + detail="attachment_ids содержат файлы из другого чата или несуществующие" + ) + + redis_key = f"idem:{user.id}:{chat_id}:{idempotency_key}" + body = payload.model_dump(mode="json") + + raw = await redis_client.get(redis_key) + if raw: + stored = json.loads(raw) + if stored["state"] == "done": + if stored["request_body"] == body: + return stored["response"] + raise HTTPException(status_code=409, detail="Idempotency-Key переиспользован с другим телом запроса") + raise HTTPException(status_code=409, detail="Запрос с этим Idempotency-Key ещё обрабатывается") + + acquired = await redis_client.set( + redis_key, + json.dumps({"state": "processing", "request_body": body}), + nx=True, + ex=86400, + ) + if not acquired: + raise HTTPException(409, "Одновременный запрос с тем же самым Idempotency-Key") + + message = Message( + chat_id=chat_id, + sender_id=user.id, + text=payload.text, + attachment_ids=[str(a) for a in payload.attachment_ids] + ) + session.add(message) + await session.commit() + await session.refresh(message) + + response_data = { + "id": str(message.id), + "chat_id": str(message.chat_id), + "sender_id": str(message.sender_id), + "text": message.text, + "created_at": message.created_at.isoformat().replace("+00:00", "Z"), + "attachment_ids": message.attachment_ids, + } + + await redis_client.set( + redis_key, + json.dumps({"state": "done", + "request_body": body, + "response": response_data}), + ex=86400, + ) + + return response_data + + +@router.get("") +async def list_messages( + chat_id: str, + limit: int = 50, + cursor: str | None = None, + user: User = Depends(get_current_user), + session: AsyncSession = Depends(get_session) +): + if limit < 1 or limit > 100: + raise HTTPException(status_code=400, detail="limit должен быть от 1 до 100") + + await check_chat_access(chat_id, user.id, session) + + offset = int(cursor) if cursor else 0 + + result = await session.execute( + select(Message) + .where(Message.chat_id == chat_id) + .order_by(Message.created_at, Message.id) + .limit(limit + 1) + .offset(offset) + ) + msgs = result.scalars().all() + + has_next = len(msgs) > limit + if has_next: + msgs = msgs[:limit] + + my_messages = [ + { + "id": m.id, + "chat_id": m.chat_id, + "sender_id": m.sender_id, + "text": m.text, + "created_at": m.created_at.isoformat().replace("+00:00", "Z"), + "attachment_ids": m.attachment_ids, + } for m in msgs + ] + + next_cursor = str(offset + limit) if has_next else None + return {"items": my_messages, "next_cursor": next_cursor} \ No newline at end of file diff --git a/app/routers/users.py b/app/routers/users.py new file mode 100644 index 00000000..b1c7515c --- /dev/null +++ b/app/routers/users.py @@ -0,0 +1,55 @@ +import uuid +from datetime import datetime +from fastapi import APIRouter, HTTPException, Depends +from pydantic import BaseModel, Field, ConfigDict, field_serializer +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy import select +from sqlalchemy.exc import IntegrityError +from app.models.user import User +from app.security import get_password_hash, get_current_user +from app.dependencies import get_session + +router = APIRouter(prefix="/api/v1/users", tags=["users"]) + +class CreateUser(BaseModel): + model_config = ConfigDict(extra="forbid") + username: str = Field(pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(min_length=1, max_length=100) + password: str = Field(min_length=5, max_length=128) + +class UserResponse(BaseModel): + id: uuid.UUID + username: str + display_name: str + created_at: datetime + model_config = ConfigDict(from_attributes=True) + + @field_serializer('created_at') + def serialize_dt(self, dt: datetime): + return dt.isoformat().replace("+00:00", "Z") + +@router.post("", status_code=201, response_model=UserResponse) +async def register_user(payload: CreateUser, session: AsyncSession = Depends(get_session)): + result = await session.execute(select(User).where(User.username == payload.username)) + if result.scalar_one_or_none(): + raise HTTPException(status_code=409, detail="Имя пользователя уже существует") + + user = User( + username=payload.username, + display_name=payload.display_name, + password_hash=await get_password_hash(payload.password) + ) + session.add(user) + + try: + await session.commit() + except IntegrityError: + await session.rollback() + raise HTTPException(status_code=409, detail="Имя пользователя уже существует") + + await session.refresh(user) + return user + +@router.get("/me", response_model=UserResponse) +async def current_user(user: User = Depends(get_current_user)): + return user \ No newline at end of file diff --git a/app/security.py b/app/security.py new file mode 100644 index 00000000..17a25bc7 --- /dev/null +++ b/app/security.py @@ -0,0 +1,104 @@ +import secrets +from datetime import datetime, timezone, timedelta +import asyncio +import hashlib +import bcrypt +from argon2 import PasswordHasher +from argon2.exceptions import VerificationError, InvalidHashError +from fastapi import Depends, HTTPException, status +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from sqlalchemy import select +from app.database import async_session_maker +from app.models.user import User +from app.redis_client import redis_client +from app.config import SESSION_TTL_SECONDS + +pwd_context = PasswordHasher( + memory_cost=19456, time_cost=2, parallelism=1, +) +password_slots = asyncio.Semaphore(2) +bearer_scheme = HTTPBearer(auto_error=False) + +async def get_password_hash(password: str) -> str: + async with password_slots: + return await asyncio.to_thread(pwd_context.hash, password) + + +def verify_password(plain: str, hashed: str) -> bool: + try: + if hashed.startswith(("$2b$", "$2a$", "$2y$")): + password = plain.encode() + return len(password) <= 72 and bcrypt.checkpw(password, hashed.encode()) + return pwd_context.verify(hashed, plain) + except (VerificationError, InvalidHashError, ValueError): + return False + + +async def check_password(plain: str, hashed: str) -> bool: + async with password_slots: + return await asyncio.to_thread(verify_password, plain, hashed) + + +def session_key(token: str) -> str: + return "session:" + hashlib.sha256(token.encode()).hexdigest() + + +async def create_session(user_id: str) -> dict: + token = secrets.token_urlsafe(32) + expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS) + + await redis_client.setex( + name=session_key(token), + time=SESSION_TTL_SECONDS, + value=str(user_id), + ) + + return { + "token": token, + "token_type": "Bearer", + "expires_at": expires_at.isoformat().replace("+00:00", "Z"), + } + + +async def delete_session(token: str) -> None: + await redis_client.delete(session_key(token)) + + +async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)): + if not credentials: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Not authenticated", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + + token = credentials.credentials + + + try: + user_id = await redis_client.get(session_key(token)) + except Exception: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Внутренняя ошибка сервера" + ) + + if not user_id: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid or expired token", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + + async with async_session_maker() as session: + result = await session.execute(select(User).where(User.id == user_id)) + user = result.scalar_one_or_none() + + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="User not found", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + + return user \ No newline at end of file diff --git a/app/serve_tls.py b/app/serve_tls.py new file mode 100644 index 00000000..42e38da3 --- /dev/null +++ b/app/serve_tls.py @@ -0,0 +1,35 @@ +"""Require a verified certificate with the ingress identity before parsing HTTP.""" +import ssl + +import uvicorn +from uvicorn.protocols.http.h11_impl import H11Protocol + + +class IngressOnlyProtocol(H11Protocol): + def connection_made(self, transport): + super().connection_made(transport) + tls = transport.get_extra_info("ssl_object") + if tls is None or ("URI", "spiffe://lab7/ingress") not in tls.getpeercert().get( + "subjectAltName", () + ): + transport.close() + return + + +if __name__ == "__main__": + config = uvicorn.Config( + "app.main:app", + host="0.0.0.0", + port=8443, + http=IngressOnlyProtocol, + proxy_headers=False, + access_log=False, + ssl_certfile="/run/identity/server.crt", + ssl_keyfile="/run/identity/server.key", + ssl_ca_certs="/run/ca/ca.crt", + ssl_cert_reqs=ssl.CERT_REQUIRED, + timeout_graceful_shutdown=5, + ) + config.load() + config.ssl.minimum_version = ssl.TLSVersion.TLSv1_2 + uvicorn.Server(config).run() diff --git a/app/storage.py b/app/storage.py new file mode 100644 index 00000000..4a52aeb3 --- /dev/null +++ b/app/storage.py @@ -0,0 +1,23 @@ +import threading +from minio import Minio +from app.transport import s3_transport +from app.config import S3_ENDPOINT, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_BUCKET + +users_lock = threading.Lock() +messages_lock = threading.Lock() + +users_by_id: dict[str, dict] = {} +users_by_username: dict[str, dict] = {} +chats_by_id: dict[str, dict] = {} +messages_by_chat: dict[str, list[dict]] = {} + +endpoint = S3_ENDPOINT.replace("http://", "").replace("https://", "") + +minio_client = Minio( + endpoint, + access_key=S3_ACCESS_KEY_ID, + secret_key=S3_SECRET_ACCESS_KEY, + **s3_transport(S3_ENDPOINT), +) + +BUCKET = S3_BUCKET \ No newline at end of file diff --git a/app/telemetry.py b/app/telemetry.py new file mode 100644 index 00000000..ea87e670 --- /dev/null +++ b/app/telemetry.py @@ -0,0 +1,136 @@ +import base64 +import logging +import os +import socket + +from opentelemetry.sdk.resources import Resource + +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor + +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader + +from opentelemetry.sdk.metrics.view import ( + View, + ExplicitBucketHistogramAggregation, +) + +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor + +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter + + +def setup_telemetry(service_name): + endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318") + username = os.environ.get("OTEL_USERNAME") + options = {} + if username: + credential = f"{username}:{os.environ['OTEL_PASSWORD']}".encode() + options = { + "certificate_file": os.environ["TLS_CA_FILE"], + "headers": {"Authorization": "Basic " + base64.b64encode(credential).decode()}, + "timeout": 5, + } + + resource = Resource.create({ + "service.name": service_name, + "service.version": "1.1.0", + "service.instance.id": socket.gethostname(), + "deployment.environment.name": "lab", + }) + + tracer_provider = TracerProvider(resource=resource) + + tracer_provider.add_span_processor( + BatchSpanProcessor( + OTLPSpanExporter( + endpoint=f"{endpoint}/v1/traces", + **options, + ) + ) + ) + + metric_reader = PeriodicExportingMetricReader( + OTLPMetricExporter( + endpoint=f"{endpoint}/v1/metrics", + **options, + ), + export_interval_millis=5000, + ) + + http_duration_view = View( + instrument_name="http_request_duration", + aggregation=ExplicitBucketHistogramAggregation( + boundaries=[ + 0.005, + 0.01, + 0.025, + 0.05, + 0.1, + 0.25, + 0.5, + 1, + 2.5, + 5, + 10, + 30, + ] + ), + ) + + job_duration_view = View( + instrument_name="job_processing_duration", + aggregation=ExplicitBucketHistogramAggregation( + boundaries=[ + 0.05, + 0.1, + 0.25, + 0.5, + 1, + 2.5, + 5, + 10, + 20, + 30, + 60, + 120, + ] + ), + ) + + meter_provider = MeterProvider( + resource=resource, + metric_readers=[metric_reader], + views=[ + http_duration_view, + job_duration_view, + ], + ) + + logger_provider = LoggerProvider(resource=resource) + + logger_provider.add_log_record_processor( + BatchLogRecordProcessor( + OTLPLogExporter( + endpoint=f"{endpoint}/v1/logs", + **options, + ) + ) + ) + + logger = logging.getLogger(service_name) + logger.setLevel(logging.INFO) + logger.propagate = False + + logger.addHandler( + LoggingHandler( + level=logging.INFO, + logger_provider=logger_provider, + ) + ) + + return tracer_provider, meter_provider, logger_provider, logger \ No newline at end of file diff --git a/app/transport.py b/app/transport.py new file mode 100644 index 00000000..127a1553 --- /dev/null +++ b/app/transport.py @@ -0,0 +1,26 @@ +import os +import ssl + +import urllib3 + + +def service_tls(): + ca = os.getenv("TLS_CA_FILE") + return ssl.create_default_context(cafile=ca) if ca else None + + +def database_tls(): + context = service_tls() + return {"ssl": context} if context else {} + + +def s3_transport(endpoint): + if not endpoint.startswith("https://"): + return {"secure": False} + return { + "secure": True, + "http_client": urllib3.PoolManager( + ssl_context=ssl.create_default_context(cafile=os.environ["TLS_CA_FILE"]), + timeout=urllib3.Timeout(connect=5, read=10), + ), + } diff --git a/app/worker.py b/app/worker.py new file mode 100644 index 00000000..f19b489e --- /dev/null +++ b/app/worker.py @@ -0,0 +1,750 @@ +import asyncio + +from app.transport import database_tls, service_tls +import hashlib +import io +import json +import os +import random +import sys +import tempfile +import time +import uuid +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import aio_pika +from minio import Minio +from app.transport import s3_transport +from PIL import Image +from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker + +from opentelemetry.trace import SpanKind, Status, StatusCode +from app.telemetry import setup_telemetry + +from app.models.attachment import Attachment +from app.models.user import User +from app.models.chat import Chat, ChatMember +from app.config import ( + DATABASE_URL, + S3_ENDPOINT, + S3_ACCESS_KEY_ID, + S3_SECRET_ACCESS_KEY, + S3_BUCKET, +) + + +RABBITMQ_URL = os.environ["RABBITMQ_URL"] + + +QUEUE_NAME = "image_tasks" + +tracer_provider, meter_provider, logger_provider, logger = setup_telemetry( + "messenger-worker" +) + +tracer = tracer_provider.get_tracer(__name__) +meter = meter_provider.get_meter(__name__) + +jobs_processed = meter.create_counter( + name="jobs_processed", + description="Total job processing attempts", + unit="1", +) + +job_processing_duration = meter.create_histogram( + name="job_processing_duration", + description="Job processing duration", + unit="s", +) + + +MAX_ATTEMPTS = max( + 1, int(os.getenv("WORKER_MAX_ATTEMPTS", "5")) +) + +CONCURRENCY = max( + 1, int(os.getenv("WORKER_CONCURRENCY", "1")) +) + +PREFETCH = max( + 1, int(os.getenv("WORKER_PREFETCH", "1")) +) + + +MAX_IMAGE_BYTES = 10 * 1024 * 1024 +PROCESS_TIMEOUT_SECONDS = 30 +LEASE_SECONDS = 300 + +endpoint = S3_ENDPOINT.replace( + "http://", "" +).replace( + "https://", "" +) + + +minio_client = Minio( + endpoint, + access_key=S3_ACCESS_KEY_ID, + secret_key=S3_SECRET_ACCESS_KEY, + **s3_transport(S3_ENDPOINT), +) + + +engine = create_async_engine(DATABASE_URL, connect_args=database_tls(), hide_parameters=True) + +async_session_maker = async_sessionmaker( + engine, + expire_on_commit=False, +) + + +class RetryableProcessingError(Exception): + def __init__(self, error_code: str): + self.error_code = error_code + super().__init__(error_code) + + +class PermanentProcessingError(Exception): + def __init__(self, error_code: str): + self.error_code = error_code + super().__init__(error_code) + + +class LeaseBusyError(Exception): + pass + + +class LeaseLostError(Exception): + pass + + +def get_rss_mb(): + try: + with open("/proc/self/status") as file: + for line in file: + if line.startswith("VmRSS:"): + kb = int(line.split()[1]) + return round(kb / 1024, 2) + except (OSError, ValueError, IndexError): + pass + + return None + + +async def claim_attachment(attachment_id: str): + async with async_session_maker() as session: + async with session.begin(): + att = await session.get( + Attachment, + uuid.UUID(attachment_id), + with_for_update=True, + ) + + if att is None: + print( + f"[Worker] Файл {attachment_id} не найден", + flush=True, + ) + return None + + if att.status == "ready" and att.thumbnail_key: + print( + f"[Worker] Файл {attachment_id} уже обработан", + flush=True, + ) + return None + + if att.status == "failed": + print( + f"[Worker] Файл {attachment_id} уже failed", + flush=True, + ) + return None + + now = datetime.now(timezone.utc) + + if ( + att.status == "processing" + and att.lease_expires_at is not None + and att.lease_expires_at > now + ): + raise LeaseBusyError() + + lease_expires_at = now + timedelta( + seconds=LEASE_SECONDS + ) + + att.status = "processing" + att.error_code = None + att.lease_expires_at = lease_expires_at + + object_key = att.object_key + + return object_key, lease_expires_at + + +async def release_lease( + attachment_id: str, + lease_expires_at: datetime, +): + async with async_session_maker() as session: + async with session.begin(): + att = await session.get( + Attachment, + uuid.UUID(attachment_id), + with_for_update=True, + ) + + if ( + att is not None + and att.status == "processing" + and att.lease_expires_at == lease_expires_at + ): + att.status = "queued" + att.lease_expires_at = None + + +async def mark_failed( + attachment_id: str, + error_code: str, +): + async with async_session_maker() as session: + async with session.begin(): + att = await session.get( + Attachment, + uuid.UUID(attachment_id), + with_for_update=True, + ) + + if att is None or att.status == "ready": + return + + if att.status == "processing": + raise LeaseBusyError() + + att.status = "failed" + att.error_code = error_code + att.lease_expires_at = None + + print( + f"[Worker] Файл {attachment_id}: " + f"failed, error_code={error_code}", + flush=True, + ) + + +async def process_image(image_data: bytes): + with tempfile.TemporaryDirectory() as temp_dir: + directory = Path(temp_dir) + + input_path = directory / "original" + input_path.write_bytes(image_data) + + try: + process = await asyncio.create_subprocess_exec( + sys.executable, + "-m", + "app.image_processor", + str(input_path), + str(directory), + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + except OSError as exc: + raise RetryableProcessingError( + "image_processor_start_error" + ) from exc + + try: + await asyncio.wait_for( + process.communicate(), + timeout=PROCESS_TIMEOUT_SECONDS, + ) + except asyncio.TimeoutError as exc: + if process.returncode is None: + try: + process.kill() + except ProcessLookupError: + pass + + await process.communicate() + + raise RetryableProcessingError( + "image_processing_timeout" + ) from exc + + if process.returncode == 20: + raise PermanentProcessingError( + "image_too_many_pixels" + ) + + if process.returncode == 21: + raise PermanentProcessingError( + "image_processing_error" + ) + + if process.returncode != 0: + raise RetryableProcessingError( + "image_processor_error" + ) + + try: + thumb_bytes = ( + directory / "thumbnail.jpg" + ).read_bytes() + + crop_bytes = ( + directory / "crop.jpg" + ).read_bytes() + + webp_bytes = ( + directory / "optimized.webp" + ).read_bytes() + + with Image.open( + io.BytesIO(thumb_bytes) + ) as thumbnail: + thumb_width, thumb_height = thumbnail.size + + except OSError as exc: + raise RetryableProcessingError( + "image_processor_output_error" + ) from exc + + return ( + thumb_bytes, + crop_bytes, + webp_bytes, + thumb_width, + thumb_height, + ) + + +async def process_attachment(attachment_id: str): + print( + f"[Worker] Обработка файла: {attachment_id}", + flush=True, + ) + + claim = await claim_attachment(attachment_id) + + if claim is None: + return "skipped" + + object_key, lease_expires_at = claim + + try: + try: + response = minio_client.get_object( + S3_BUCKET, + object_key, + ) + + try: + image_data = response.read( + MAX_IMAGE_BYTES + 1 + ) + finally: + response.close() + response.release_conn() + + except Exception as exc: + raise RetryableProcessingError( + "s3_download_error" + ) from exc + + if len(image_data) > MAX_IMAGE_BYTES: + raise PermanentProcessingError( + "image_too_large" + ) + + ( + thumb_bytes, + crop_bytes, + webp_bytes, + thumb_width, + thumb_height, + ) = await process_image(image_data) + + thumb_key = f"thumbnails/{object_key}" + crop_key = f"crops/{attachment_id}.jpg" + webp_key = f"webp/{attachment_id}.webp" + + try: + minio_client.put_object( + S3_BUCKET, + thumb_key, + io.BytesIO(thumb_bytes), + len(thumb_bytes), + content_type="image/jpeg", + ) + + minio_client.put_object( + S3_BUCKET, + crop_key, + io.BytesIO(crop_bytes), + len(crop_bytes), + content_type="image/jpeg", + ) + + minio_client.put_object( + S3_BUCKET, + webp_key, + io.BytesIO(webp_bytes), + len(webp_bytes), + content_type="image/webp", + ) + + except Exception as exc: + raise RetryableProcessingError( + "s3_upload_error" + ) from exc + + async with async_session_maker() as session: + async with session.begin(): + att = await session.get( + Attachment, + uuid.UUID(attachment_id), + with_for_update=True, + ) + + if ( + att is None + or att.status != "processing" + or att.lease_expires_at != lease_expires_at + ): + raise LeaseLostError() + + att.thumbnail_key = thumb_key + att.thumbnail_sha256 = hashlib.sha256( + thumb_bytes + ).hexdigest() + att.thumbnail_size_bytes = len(thumb_bytes) + att.thumbnail_width = thumb_width + att.thumbnail_height = thumb_height + att.crop_key = crop_key + att.webp_key = webp_key + att.status = "ready" + att.error_code = None + att.lease_expires_at = None + + print( + f"[Worker] Успешно обработан {attachment_id}", + flush=True, + ) + + return "success" + + except Exception: + await release_lease( + attachment_id, + lease_expires_at, + ) + raise + + +async def main(): + connection = await aio_pika.connect_robust( + RABBITMQ_URL, ssl_context=service_tls() + ) + + async with connection: + channel = await connection.channel( + publisher_confirms=True + ) + + await channel.set_qos( + prefetch_count=PREFETCH + ) + + queue = await channel.declare_queue( + QUEUE_NAME, + durable=True, + ) + + semaphore = asyncio.Semaphore(CONCURRENCY) + + print( + f"[Worker] CONCURRENCY={CONCURRENCY}, " + f"PREFETCH={PREFETCH}", + flush=True, + ) + + async def on_message( + message: aio_pika.IncomingMessage + ): + async with semaphore: + started = time.perf_counter() + + outcome = "failed" + + with tracer.start_as_current_span( + "image_tasks process", + kind=SpanKind.CONSUMER, + record_exception=False, + set_status_on_exception=False, + ) as span: + + span.set_attribute( + "messaging.system", "rabbitmq" + ) + span.set_attribute( + "messaging.destination.name", QUEUE_NAME + ) + + try: + try: + data = json.loads( + message.body.decode() + ) + + attachment_id = str( + uuid.UUID(data["attachment_id"]) + ) + + except ( + ValueError, + KeyError, + TypeError, + ): + print( + "[Worker] Некорректное сообщение", + flush=True, + ) + + await message.reject( + requeue=False + ) + return + + headers = dict(message.headers or {}) + + try: + attempt = max( + 1, + int(headers.get("x-attempt", 1)), + ) + except (ValueError, TypeError): + attempt = 1 + + print( + f"[Worker] Попытка " + f"{attempt}/{MAX_ATTEMPTS} " + f"для {attachment_id}", + flush=True, + ) + + try: + result = await process_attachment( + attachment_id + ) + + except LeaseBusyError: + print( + "[Worker] Задание уже " + "обрабатывается, ждём Lease", + flush=True, + ) + + await asyncio.sleep(5) + + await message.nack( + requeue=True + ) + + outcome = "retry" + return + + except LeaseLostError: + print( + "[Worker] Lease перешёл " + "другому Worker", + flush=True, + ) + + await message.ack() + + outcome = "skipped" + return + + except PermanentProcessingError as exc: + try: + await mark_failed( + attachment_id, + exc.error_code, + ) + except Exception: + await message.nack( + requeue=True + ) + + outcome = "retry" + return + + await message.ack() + + outcome = "failed" + return + + except Exception as exc: + error_code = ( + exc.error_code + if isinstance( + exc, + RetryableProcessingError, + ) + else "worker_error" + ) + + if attempt < MAX_ATTEMPTS: + next_attempt = attempt + 1 + + print( + f"[Worker] Ошибка {error_code}. " + f"Повтор " + f"{next_attempt}/{MAX_ATTEMPTS}", + flush=True, + ) + + headers["x-attempt"] = next_attempt + + base_delay = min( + 30, + 2 ** (attempt - 1), + ) + + delay = base_delay + random.uniform( + 0, + base_delay / 2, + ) + + print( + f"[Worker] Повтор через " + f"{delay:.1f} сек.", + flush=True, + ) + + await asyncio.sleep(delay) + + try: + await channel.default_exchange.publish( + aio_pika.Message( + body=message.body, + headers=headers, + delivery_mode=( + aio_pika.DeliveryMode.PERSISTENT + ), + content_type="application/json", + ), + routing_key=QUEUE_NAME, + ) + + except Exception: + await message.nack( + requeue=True + ) + + outcome = "retry" + return + + await message.ack() + + outcome = "retry" + return + + print( + f"[Worker] Попытки исчерпаны: " + f"{attachment_id}", + flush=True, + ) + + try: + await mark_failed( + attachment_id, + error_code, + ) + except Exception: + await message.nack( + requeue=True + ) + + outcome = "retry" + return + + await message.ack() + + outcome = "failed" + return + + await message.ack() + + outcome = result + + duration = time.perf_counter() - started + rss_mb = get_rss_mb() + + print( + f"[Metrics] attachment_id={attachment_id} " + f"duration_s={duration:.3f} " + f"rss_mb={rss_mb}", + flush=True, + ) + + finally: + duration = time.perf_counter() - started + + attributes = { + "job_type": "image_processing", + "outcome": outcome, + } + + jobs_processed.add( + 1, + attributes, + ) + + job_processing_duration.record( + duration, + attributes, + ) + + span.set_attribute( + "job.type", + "image_processing", + ) + + span.set_attribute( + "job.outcome", + outcome, + ) + + if outcome in ("failed", "retry"): + span.set_status( + Status(StatusCode.ERROR) + ) + + logger.log( + 40 if outcome == "failed" + else 30 if outcome == "retry" + else 20, + "job_processing_completed", + extra={ + "event": "job_processing_completed", + "job_type": "image_processing", + "outcome": outcome, + "duration_seconds": duration, + }, + ) + + print( + "[Worker] Ждем сообщения из RabbitMQ...", + flush=True, + ) + + await queue.consume(on_message) + await asyncio.Future() + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a9777..d6dba98e 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -1,23 +1,23 @@ -# Матрица доверия — заполнить в решении lab7 +# Матрица доверия — lab7, уровень 3 Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. | Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | | --- | --- | --- | --- | -| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | -| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | -| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | -| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO | -| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | -| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO | -| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO | -| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO | -| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO | -| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO | -| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO | -| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO | +| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | `https://localhost:8443`, CA lab7, SAN localhost, Bearer с Redis TTL 3600 с. `make test`, `make test-security`, `tests/grade3_api.py`. | +| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | `app1:8443` и `app2:8443`, CA lab7, Nginx проверяет SAN `api.internal`, обе реплики проверяют URI SAN `spiffe://lab7/ingress`. Срок leaf 90 дней. `docker compose run --rm --no-deps verify -m scripts.verify_lab7`. | +| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | `db:5432`, TLS verify-full, SAN db. Отдельные `messenger_api`, `messenger_worker`, `messenger_outbox` и `messenger_migrate`. Права таблиц и столбцов в `infra/security/database-grants.sql`. Пароли KV. Health из сокета процесса; внешний TCP только TLS. | +| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | `https://minio:9000`, CA lab7, SAN minio. Отдельные API и worker ключи к одному приватному bucket. У API запись в `originals/`, у worker запись в `thumbnails/`, `crops/`, `webp/`. Чтение объектов bucket включает ранее записанные пути. Пароли KV. | +| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | `amqps://rabbitmq:5671/jobs`, SAN rabbitmq, TLS с CA. Outbox публикует в отдельном vhost, worker читает и публикует повторные попытки, оба объявляют только `image_tasks`. Права в сгенерированных definitions. У API нет прямого AMQP-доступа. | +| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | `https://telemetry:8444/ingest/v1/…`, CA lab7, SAN telemetry. У API и worker разные Basic-credentials. Незарегистрированный запрос получает 401. Nginx передаёт OTLP только на loopback `127.0.0.1:14318` общей области наблюдаемости. | +| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | Collector отправляет записи через TLS на `telemetry:8444/loki-write` и `/tempo-write` с отдельным доступом к записи. Backend-порты слушают loopback. Prometheus собирает `/metrics` и `/collector-metrics` через тот же TLS с отдельным аккаунтом. | +| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | Grafana запрашивает `https://telemetry:8444/{prometheus,loki,tempo}`, SAN telemetry, CA lab7. Отдельный Basic-пользователь только для путей чтения. Административные URL backends на TLS-шлюзе отсутствуют. | +| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | `https://openbao:8200`, SAN openbao, CA lab7. AppRole отдельно для API, worker, outbox и миграций. SecretID 30 дней, рабочий токен 5 минут и отзывается при старте сразу после чтения. Проверка 403 для чужого пути и записи политики через `scripts.verify_lab7`. | +| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | OpenBao `https://localhost:8200`, Grafana `https://localhost:3443`, только loopback хоста. Оператор инициализирует OpenBao с долями разблокировки, Grafana использует отдельного администратора. S3 администрируется через TLS из одноразового Compose-сервиса оператора, наружу порт не опубликован. | +| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | `rediss://redis:6380`, CA lab7, SAN redis. ACL пользователя API разрешает только команды и ключи `session:*` и `idem:*`. Пароль KV. Простого Redis-listener нет. | +| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | N/A. Один экземпляр каждого хранилища и брокера. Отказоустойчивость демонстрируется на двух репликах API. | -Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. +Health API доступен только на TLS-порту реплики с той же проверкой mTLS. В общей сетевой области наблюдаемости HTTP-порты Collector, Loki, Tempo, Prometheus и Grafana слушают loopback. За пределами области доступны только HTTPS-listeners шлюза. Grafana и OpenBao публикуются только на loopback хоста. Пароли хранилищ и телеметрии статические, с раздельными правами и операторской заменой. ## Обязательные отрицательные проверки diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..2c0e7820 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,256 @@ +x-app: &application + image: "${COMPOSE_PROJECT_NAME:-mtusi2026lab7}-app:local" + build: . + entrypoint: ["python", "-m", "app.bao"] + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + mem_limit: 512m + cpus: 0.75 + restart: "on-failure:5" + +x-app-env: &application-environment + BAO_ADDR: https://openbao:8200 + TLS_CA_FILE: /run/ca/ca.crt + S3_BUCKET: messenger-attachments + S3_ENDPOINT: https://minio:9000 + S3_REGION: us-east-1 + OTEL_EXPORTER_OTLP_ENDPOINT: https://telemetry:8444/ingest + SESSION_TTL_SECONDS: "${SESSION_TTL_SECONDS:-3600}" + +services: + db: + image: postgres:16-alpine@sha256:f2f98726820d0342055351c6e9d36e705f5bfffb3dd53ff556325114b08afb6d + entrypoint: ["/bin/sh", "/etc/lab7/postgres.sh"] + environment: + POSTGRES_USER: messenger_admin + POSTGRES_DB: messenger_db + volumes: + - postgres_data:/var/lib/postgresql/data + - ./infra/security:/etc/lab7:ro + - ${LAB7_STATE:-./secrets/lab7}/db:/run/identity:ro + healthcheck: + test: ["CMD", "pg_isready", "-U", "messenger_admin", "-d", "messenger_db"] + interval: 3s + timeout: 3s + retries: 20 + + redis: + image: redis:7-alpine@sha256:7f7d30b7fdd09467bac58198a1f166dd69789d348d4fe859cccb20e0cf287fbe + command: ["redis-server", "/etc/lab7/redis.conf"] + volumes: + - redis_data:/data + - ./infra/security/redis.conf:/etc/lab7/redis.conf:ro + - ${LAB7_STATE:-./secrets/lab7}/redis:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + + rabbitmq: + image: rabbitmq:3.12-management-alpine@sha256:0b44fbcc3a4bf22d00090f1353127577dbe1fcb109c41669733a9d7ecf6c3a78 + environment: + ERL_EPMD_ADDRESS: 127.0.0.1 + RABBITMQ_NODENAME: rabbit@localhost + volumes: + - rabbitmq_data:/var/lib/rabbitmq + - ./infra/security/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro + - ./infra/security/rabbitmq-plugins.conf:/etc/rabbitmq/enabled_plugins:ro + - ${LAB7_STATE:-./secrets/lab7}/rabbitmq:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + + minio: + image: pgsty/silo@sha256:c20d112390b9a9ce8c11b8af95ad35bcaa62f4759663c09c936cd8d2b511f329 + entrypoint: ["/bin/sh", "-ec"] + command: + - | + export MINIO_ROOT_USER=messenger-admin + export MINIO_ROOT_PASSWORD="$$(cat /run/identity/admin_password)" + exec silo server /data --certs-dir /run/identity --console-address 127.0.0.1:9001 + volumes: + - minio_data:/data + - ${LAB7_STATE:-./secrets/lab7}/minio:/run/identity:ro + + minio-init: + image: pgsty/mc@sha256:b532278b7a3747dbab6fe45eebb40a653efa704e6758e24e9d9ec54fc96c1800 + profiles: [operator] + entrypoint: ["/bin/sh", "/etc/lab7/minio-init.sh"] + volumes: + - ./infra/security/minio-init.sh:/etc/lab7/minio-init.sh:ro + - ${LAB7_STATE:-./secrets/lab7}/minio-init:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + + openbao: + image: openbao/openbao:2.4.4 + command: ["server", "-config=/etc/bao/server.hcl"] + environment: + BAO_ADDR: https://openbao:8200 + BAO_API_ADDR: https://openbao:8200 + BAO_CACERT: /run/ca/ca.crt + SKIP_SETCAP: "true" + ports: + - "127.0.0.1:${BAO_HOST_PORT:-8200}:8200" + volumes: + - openbao_data:/openbao/file + - ./infra/openbao/server.hcl:/etc/bao/server.hcl:ro + - ${LAB7_STATE:-./secrets/lab7}/openbao:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + + migrate: + <<: *application + profiles: [operator] + restart: "no" + command: ["alembic", "upgrade", "head"] + environment: + <<: *application-environment + BAO_ROLE: migrate + volumes: + - ${LAB7_STATE:-./secrets/lab7}/migrate:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + + app1: + <<: *application + command: ["python", "-m", "app.serve_tls"] + environment: + <<: *application-environment + BAO_ROLE: api + volumes: + - ${LAB7_STATE:-./secrets/lab7}/app1:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + + app2: + <<: *application + command: ["python", "-m", "app.serve_tls"] + environment: + <<: *application-environment + BAO_ROLE: api + volumes: + - ${LAB7_STATE:-./secrets/lab7}/app2:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + + worker: + <<: *application + command: ["python", "-m", "app.worker"] + environment: + <<: *application-environment + BAO_ROLE: worker + volumes: + - ${LAB7_STATE:-./secrets/lab7}/worker:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + + outbox: + <<: *application + command: ["python", "-m", "app.outbox_dispatcher"] + environment: + <<: *application-environment + BAO_ROLE: outbox + volumes: + - ${LAB7_STATE:-./secrets/lab7}/outbox:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + + nginx: + image: nginx@sha256:7fc0fb4af7bf006aeb31aea88069976060f8f0a0a86b667126742cc17f4e31ae + user: "101:101" + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + ports: + - "127.0.0.1:${HTTPS_PORT:-8443}:8443" + volumes: + - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro + - ${LAB7_STATE:-./secrets/lab7}/nginx:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + depends_on: [app1, app2] + + telemetry: + image: nginx@sha256:7fc0fb4af7bf006aeb31aea88069976060f8f0a0a86b667126742cc17f4e31ae + user: "101:101" + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + ports: + - "127.0.0.1:${GRAFANA_HTTPS_PORT:-3443}:3443" + volumes: + - ./infra/security/telemetry.nginx.conf:/etc/nginx/nginx.conf:ro + - ${LAB7_STATE:-./secrets/lab7}/telemetry:/run/identity:ro + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.123.0 + network_mode: "service:telemetry" + command: + - "--config=/etc/otelcol-contrib/collector.yaml" + - "--config=/run/identity/collector.json" + volumes: + - ./infra/otel/collector.yaml:/etc/otelcol-contrib/collector.yaml:ro + - ${LAB7_STATE:-./secrets/lab7}/collector:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + mem_limit: 256m + + prometheus: + image: prom/prometheus:v3.2.1 + network_mode: "service:telemetry" + command: + - "--config.file=/etc/prometheus/prometheus.yml" + - "--storage.tsdb.path=/prometheus" + - "--storage.tsdb.retention.time=7d" + - "--web.listen-address=127.0.0.1:9090" + volumes: + - ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - ${LAB7_STATE:-./secrets/lab7}/prometheus:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + - prometheus_data:/prometheus + mem_limit: 512m + + loki: + image: grafana/loki:3.4.2 + network_mode: "service:telemetry" + command: ["-config.file=/etc/loki/loki.yml"] + volumes: + - ./infra/loki/loki.yml:/etc/loki/loki.yml:ro + - loki_data:/loki + mem_limit: 512m + + tempo: + image: grafana/tempo:2.7.1 + network_mode: "service:telemetry" + user: "0:0" + command: ["-config.file=/etc/tempo/tempo.yml"] + volumes: + - ./infra/tempo/tempo.yml:/etc/tempo/tempo.yml:ro + - tempo_data:/var/tempo + mem_limit: 512m + + grafana: + image: grafana/grafana:11.5.2 + network_mode: "service:telemetry" + environment: + GF_SERVER_HTTP_ADDR: 127.0.0.1 + GF_SERVER_ROOT_URL: "https://localhost:${GRAFANA_HTTPS_PORT:-3443}/" + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/identity/admin_password + GF_SECURITY_COOKIE_SECURE: "true" + GF_USERS_ALLOW_SIGN_UP: "false" + GF_AUTH_ANONYMOUS_ENABLED: "false" + GF_ANALYTICS_REPORTING_ENABLED: "false" + volumes: + - grafana_data:/var/lib/grafana + - ./infra/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro + - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro + - ${LAB7_STATE:-./secrets/lab7}/grafana/datasources:/etc/grafana/provisioning/datasources:ro + - ${LAB7_STATE:-./secrets/lab7}/grafana/admin:/run/identity:ro + mem_limit: 512m + + verify: + <<: *application + profiles: [operator] + entrypoint: ["python"] + restart: "no" + environment: + BAO_ADDR: https://openbao:8200 + volumes: + - ${LAB7_STATE:-./secrets/lab7}/verify:/run/identity:ro + - ${LAB7_STATE:-./secrets/lab7}/ca:/run/ca:ro + +volumes: + postgres_data: + redis_data: + minio_data: + rabbitmq_data: + openbao_data: + prometheus_data: + loki_data: + tempo_data: + grafana_data: diff --git a/evidence/lab7-grade3.txt b/evidence/lab7-grade3.txt new file mode 100644 index 00000000..40a50c3b --- /dev/null +++ b/evidence/lab7-grade3.txt @@ -0,0 +1,77 @@ +Lab7 — Docker Desktop, Apple M3 Pro, локальные синтетические данные + +make check +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. + +make validate +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. + +docker compose config --quiet +Код выхода 0. + +make test CA_FILE=secrets/lab7/ca/ca.crt +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. + +make test-security CA_FILE=secrets/lab7/ca/ca.crt +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. + +docker compose run --rm --no-deps verify -m scripts.verify_lab7 +PASS app1: correct LB certificate only +PASS app2: correct LB certificate only +PASS OpenBao api: own secret allowed, cross-role read and policy write denied +PASS OpenBao worker: own secret allowed, cross-role read and policy write denied +PASS telemetry does not allow ingestion without service credentials + +python3 tests/grade3_api.py --ca-file secrets/lab7/ca/ca.crt +PASS HTTPS rejects an incorrect hostname with the trusted CA +PASS attachment cannot be linked into another chat +PASS oversized body returns 413 +PASS login limit returns 429 with Retry-After + +tests/grade3_api.py --expiry-only, отдельный стенд SESSION_TTL_SECONDS=8 +PASS HTTPS session works before TTL and returns 401 after expiry + +python3 tests/test_worker_retry.py --ca-file secrets/lab7/ca/ca.crt +PASS HTTPS worker retry reached failed with s3_download_error + +python3 scripts/check_telemetry.py +PASS Grafana → Prometheus: API and worker counters and histograms +PASS Grafana → Loki → Tempo: messenger-api +PASS Grafana → Loki → Tempo: messenger-worker + +make test-persistence CA_FILE=secrets/lab7/ca/ca.crt ACTION_SCRIPT=scripts/restart.sh +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. + +make test-failover CA_FILE=secrets/lab7/ca/ca.crt ACTION_SCRIPT=scripts/stop-one.sh +{"observed_instances_before": 2, "successful_writes": 120, "failed_attempts": 0, "first_recovery_seconds": 0.832} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. + +Последовательная остановка реплик через scripts/stop-one.sh и HTTPS readiness +PASS HTTPS readiness with app1 stopped +PASS HTTPS readiness with app2 stopped + +docker compose exec -T app1 python -m app.bao python -m scripts.bench_password +hash: n=40, p50=12.99 ms, p95=40.42 ms +verify: n=40, p50=12.17 ms, p95=40.12 ms + +Повторная проверка из чистого состояния на отдельном Compose-проекте +Публичный HTTPS smoke, тест внешнего TLS, внутренний mTLS, OpenBao, ACL, +лимиты, тест worker, проверка телеметрии и истечение сессии повторно прошли. + +PASS PostgreSQL api: verified TLS, plaintext rejected, role permissions checked +PASS PostgreSQL worker: verified TLS, plaintext rejected, role permissions checked +PASS Redis: verified TLS, PING allowed, out-of-scope key denied +PASS RabbitMQ: verified TLS with worker credentials +PASS S3: verified TLS, API and worker cannot write into each other's prefixes +PASS OpenBao: API and worker have scoped tokens bounded to 300 seconds; revoked tokens were denied +PASS Docker: only three loopback ports; API and worker non-root, zero capabilities, 512 MiB/0.75 CPU +PASS Argon2id: 10 test users, 19 MiB/t=2/p=1, unique salts +PASS Secret isolation: operator files protected; generated secrets absent from container config, logs and sampled Loki entries +PASS Application image excludes local secrets and private keys. + +PASS: persistence preserved confirmed data and existing session. +{"observed_instances_before": 2, "successful_writes": 118, "failed_attempts": 0, "first_recovery_seconds": 1.647} +PASS: failover preserved confirmed data and existing session. +Последовательно отключены обе реплики, по одной. При отключении app1 первый +отдельный readiness-запрос получил 504, повторный запрос получил 200. +При отключении app2 readiness получил 200. diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json new file mode 100644 index 00000000..1fd2b446 --- /dev/null +++ b/infra/grafana/dashboards/messenger.json @@ -0,0 +1,191 @@ +{ + "uid": "messenger-observability", + "title": "Messenger — Observability", + "tags": ["messenger", "lab6"], + "timezone": "browser", + "schemaVersion": 39, + "version": 1, + "refresh": "5s", + "editable": false, + "time": { + "from": "now-15m", + "to": "now" + }, + "panels": [ + { + "id": 1, + "title": "HTTP Requests / sec", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 0 + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rate(http_requests_total{service_name=\"messenger-api\"}[1m]))", + "legendFormat": "Requests/sec" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps", + "min": 0 + }, + "overrides": [] + } + }, + { + "id": 2, + "title": "HTTP Error Ratio", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 0 + }, + "targets": [ + { + "refId": "A", + "expr": "100 * (sum(rate(http_requests_total{service_name=\"messenger-api\",status_class=\"5xx\"}[1m])) or 0 * sum(rate(http_requests_total{service_name=\"messenger-api\"}[1m]))) / sum(rate(http_requests_total{service_name=\"messenger-api\"}[1m]))", + "legendFormat": "5xx errors" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percent", + "min": 0, + "max": 100 + }, + "overrides": [] + } + }, + { + "id": 3, + "title": "HTTP Duration p95", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 0 + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket{service_name=\"messenger-api\"}[1m]) and ignoring(le) http_request_duration_seconds_bucket{service_name=\"messenger-api\",le=\"0.005\"}))", + "legendFormat": "HTTP p95" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "min": 0 + }, + "overrides": [] + } + }, + { + "id": 4, + "title": "Job Attempts / sec", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 0, + "y": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rate(jobs_processed_total{service_name=\"messenger-worker\"}[1m]))", + "legendFormat": "Attempts/sec" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops", + "min": 0 + }, + "overrides": [] + } + }, + { + "id": 5, + "title": "Job Outcomes", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 8, + "y": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (outcome) (jobs_processed_total{service_name=\"messenger-worker\"})", + "legendFormat": "{{outcome}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "min": 0 + }, + "overrides": [] + } + }, + { + "id": 6, + "title": "Job Duration p95", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "h": 8, + "w": 8, + "x": 16, + "y": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.95, sum by (le) (rate(job_processing_duration_seconds_bucket{service_name=\"messenger-worker\"}[1m]) and ignoring(le) job_processing_duration_seconds_bucket{service_name=\"messenger-worker\",le=\"0.05\"}))", + "legendFormat": "Worker p95" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "min": 0 + }, + "overrides": [] + } + } + ] +} \ No newline at end of file diff --git a/infra/grafana/provisioning/dashboards/dashboards.yml b/infra/grafana/provisioning/dashboards/dashboards.yml new file mode 100644 index 00000000..cb8e2261 --- /dev/null +++ b/infra/grafana/provisioning/dashboards/dashboards.yml @@ -0,0 +1,13 @@ +apiVersion: 1 + +providers: + - name: Messenger + orgId: 1 + folder: Messenger + type: file + disableDeletion: true + editable: false + updateIntervalSeconds: 10 + + options: + path: /var/lib/grafana/dashboards diff --git a/infra/grafana/provisioning/datasources/datasources.yml b/infra/grafana/provisioning/datasources/datasources.yml new file mode 100644 index 00000000..dcd4e015 --- /dev/null +++ b/infra/grafana/provisioning/datasources/datasources.yml @@ -0,0 +1,47 @@ +{ + "apiVersion": 1, + "datasources": [ + { + "name": "Prometheus", + "uid": "prometheus", + "type": "prometheus", + "access": "proxy", + "url": "https://telemetry:8444/prometheus", + "isDefault": true, + "editable": false, + "basicAuth": true, + "basicAuthUser": "grafana", + "jsonData": { + "tlsAuthWithCACert": true + } + }, + { + "name": "Loki", + "uid": "loki", + "type": "loki", + "access": "proxy", + "url": "https://telemetry:8444/loki", + "isDefault": false, + "editable": false, + "basicAuth": true, + "basicAuthUser": "grafana", + "jsonData": { + "tlsAuthWithCACert": true + } + }, + { + "name": "Tempo", + "uid": "tempo", + "type": "tempo", + "access": "proxy", + "url": "https://telemetry:8444/tempo", + "isDefault": false, + "editable": false, + "basicAuth": true, + "basicAuthUser": "grafana", + "jsonData": { + "tlsAuthWithCACert": true + } + } + ] +} diff --git a/infra/lab6-baseline.md b/infra/lab6-baseline.md new file mode 100644 index 00000000..b1b91298 --- /dev/null +++ b/infra/lab6-baseline.md @@ -0,0 +1,3 @@ +# База lab6 + +Из lab6 перенесены FastAPI, Alembic, PostgreSQL, Redis, S3, RabbitMQ, обработчик вложений, transactional outbox и наблюдаемость. Текущий `docker-compose.yml` запускает защищённый стенд lab7. Параметры, порядок запуска и команды проверок приведены в [отчёте lab7](../REPORT.md). diff --git a/infra/loki/loki.yml b/infra/loki/loki.yml new file mode 100644 index 00000000..4dbf1765 --- /dev/null +++ b/infra/loki/loki.yml @@ -0,0 +1,38 @@ +auth_enabled: false + +server: + http_listen_address: 127.0.0.1 + grpc_listen_address: 127.0.0.1 + grpc_listen_port: 9096 + http_listen_port: 3100 + +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + + replication_factor: 1 + + ring: + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +limits_config: + allow_structured_metadata: true + +analytics: + reporting_enabled: false diff --git a/infra/openbao/README.md b/infra/openbao/README.md index 0850e237..b323d176 100644 --- a/infra/openbao/README.md +++ b/infra/openbao/README.md @@ -1,7 +1,5 @@ -# OpenBao — реализовать конфигурацию и политики +# OpenBao в стенде lab7 -Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key. +Сервер использует TLS и зашифрованное файловое хранилище в именованном томе. Оператор с хоста запускает `python3 scripts/lab7.py up`. Bootstrap создаёт три доли разблокировки с порогом два и хранит их в защищённом операторском каталоге. Процессы приложения получают собственные файлы AppRole через bind mount и обращаются к OpenBao через TLS. -Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения. - -Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md. +Политика каждой роли разрешает один путь `messenger/data/<роль>`. Токен действует до пяти минут и отзывается после чтения. После остановки OpenBao оператор выполняет `python3 scripts/lab7.py unseal`. Команды запуска и проверки политик есть в [отчёте](../../REPORT.md). diff --git a/infra/openbao/server.hcl b/infra/openbao/server.hcl new file mode 100644 index 00000000..10c2c708 --- /dev/null +++ b/infra/openbao/server.hcl @@ -0,0 +1,13 @@ +ui = false +disable_mlock = true + +storage "file" { + path = "/openbao/file" +} + +listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/run/identity/server.crt" + tls_key_file = "/run/identity/server.key" + tls_min_version = "tls12" +} diff --git a/infra/openbao/service-policy.hcl b/infra/openbao/service-policy.hcl new file mode 100644 index 00000000..64eb1bbf --- /dev/null +++ b/infra/openbao/service-policy.hcl @@ -0,0 +1,3 @@ +path "messenger/data/ROLE_NAME" { + capabilities = ["read"] +} diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 00000000..4117a01c --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,61 @@ +receivers: + otlp: + protocols: + http: + endpoint: 127.0.0.1:14318 + +extensions: + basicauth/collector: + client_auth: + username: collector + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 192 + spike_limit_mib: 48 + batch: + timeout: 1s + send_batch_size: 512 + +exporters: + prometheus: + endpoint: 127.0.0.1:8889 + resource_to_telemetry_conversion: + enabled: true + otlphttp/loki: + logs_endpoint: https://telemetry:8444/loki-write + tls: + ca_file: /run/ca/ca.crt + auth: + authenticator: basicauth/collector + otlphttp/tempo: + traces_endpoint: https://telemetry:8444/tempo-write + tls: + ca_file: /run/ca/ca.crt + auth: + authenticator: basicauth/collector + +service: + extensions: [basicauth/collector] + telemetry: + metrics: + readers: + - pull: + exporter: + prometheus: + host: 127.0.0.1 + port: 8888 + pipelines: + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/loki] + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlphttp/tempo] diff --git a/infra/prometheus/prometheus.yml b/infra/prometheus/prometheus.yml new file mode 100644 index 00000000..5a7b1eec --- /dev/null +++ b/infra/prometheus/prometheus.yml @@ -0,0 +1,25 @@ +global: + scrape_interval: 5s + evaluation_interval: 5s + +scrape_configs: + - job_name: otel-collector + scheme: https + static_configs: + - targets: ["telemetry:8444"] + tls_config: + ca_file: /run/ca/ca.crt + basic_auth: + username: prometheus + password_file: /run/identity/scrape_password + + - job_name: collector-internal + scheme: https + metrics_path: /collector-metrics + static_configs: + - targets: ["telemetry:8444"] + tls_config: + ca_file: /run/ca/ca.crt + basic_auth: + username: prometheus + password_file: /run/identity/scrape_password diff --git a/infra/security/database-grants.sql b/infra/security/database-grants.sql new file mode 100644 index 00000000..08249736 --- /dev/null +++ b/infra/security/database-grants.sql @@ -0,0 +1,16 @@ +-- API owns business operations. The two background processes have separate roles. +GRANT SELECT, INSERT ON users, chats, chat_members, messages TO messenger_api; +GRANT SELECT, INSERT ON attachments TO messenger_api; +GRANT INSERT ON outbox_events TO messenger_api; +GRANT SELECT (created_at) ON outbox_events TO messenger_api; + +GRANT SELECT ON attachments TO messenger_worker; +GRANT UPDATE (status, error_code, updated_at, lease_expires_at, thumbnail_key, + thumbnail_sha256, thumbnail_size_bytes, thumbnail_width, + thumbnail_height, crop_key, webp_key) + ON attachments TO messenger_worker; + +GRANT SELECT ON attachments, outbox_events TO messenger_outbox; +GRANT UPDATE (status, lease_expires_at, updated_at) ON attachments TO messenger_outbox; +GRANT INSERT ON outbox_events TO messenger_outbox; +GRANT UPDATE (published_at) ON outbox_events TO messenger_outbox; diff --git a/infra/security/minio-init.sh b/infra/security/minio-init.sh new file mode 100644 index 00000000..2cd59497 --- /dev/null +++ b/infra/security/minio-init.sh @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu +mkdir -p /tmp/mc/certs/CAs +cp /run/ca/ca.crt /tmp/mc/certs/CAs/lab7.crt +export MC_CONFIG_DIR=/tmp/mc +attempt=0 +until mc alias set storage https://minio:9000 messenger-admin "$(cat /run/identity/admin_password)" >/dev/null 2>&1; do + attempt=$((attempt + 1)) + [ "$attempt" -lt 30 ] || exit 1 + sleep 1 +done +mc mb --ignore-existing storage/messenger-attachments +mc anonymous set none storage/messenger-attachments +for role in api worker; do + mc admin user add storage "messenger-$role" "$(cat "/run/identity/${role}_password")" >/dev/null + mc admin policy create storage "messenger-$role" "/run/identity/${role}_policy.json" + mc admin policy attach storage "messenger-$role" --user "messenger-$role" +done diff --git a/infra/security/pg_hba.conf b/infra/security/pg_hba.conf new file mode 100644 index 00000000..c7afa9eb --- /dev/null +++ b/infra/security/pg_hba.conf @@ -0,0 +1,3 @@ +local all all trust +hostssl all all 0.0.0.0/0 scram-sha-256 +hostssl all all ::/0 scram-sha-256 diff --git a/infra/security/postgres.sh b/infra/security/postgres.sh new file mode 100644 index 00000000..e0f631f4 --- /dev/null +++ b/infra/security/postgres.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu +install -d -m 0700 -o postgres -g postgres /tmp/db-tls +install -m 0600 -o postgres -g postgres /run/identity/server.key /tmp/db-tls/server.key +install -m 0644 -o postgres -g postgres /run/identity/server.crt /tmp/db-tls/server.crt +export POSTGRES_PASSWORD_FILE=/run/identity/admin_password +exec docker-entrypoint.sh postgres \ + -c ssl=on -c ssl_cert_file=/tmp/db-tls/server.crt -c ssl_key_file=/tmp/db-tls/server.key \ + -c hba_file=/etc/lab7/pg_hba.conf -c password_encryption=scram-sha-256 diff --git a/infra/security/rabbitmq-plugins.conf b/infra/security/rabbitmq-plugins.conf new file mode 100644 index 00000000..57afcca0 --- /dev/null +++ b/infra/security/rabbitmq-plugins.conf @@ -0,0 +1 @@ +[]. diff --git a/infra/security/rabbitmq.conf b/infra/security/rabbitmq.conf new file mode 100644 index 00000000..32f9d402 --- /dev/null +++ b/infra/security/rabbitmq.conf @@ -0,0 +1,10 @@ +listeners.tcp = none +listeners.ssl.default = 5671 +ssl_options.cacertfile = /run/ca/ca.crt +ssl_options.certfile = /run/identity/server.crt +ssl_options.keyfile = /run/identity/server.key +ssl_options.verify = verify_none +ssl_options.fail_if_no_peer_cert = false +distribution.listener.interface = 127.0.0.1 +definitions.import_backend = local_filesystem +definitions.local.path = /run/identity/definitions.json diff --git a/infra/security/redis.conf b/infra/security/redis.conf new file mode 100644 index 00000000..d25ae259 --- /dev/null +++ b/infra/security/redis.conf @@ -0,0 +1,9 @@ +port 0 +tls-port 6380 +tls-cert-file /run/identity/server.crt +tls-key-file /run/identity/server.key +tls-ca-cert-file /run/ca/ca.crt +tls-auth-clients no +aclfile /run/identity/users.acl +appendonly yes +dir /data diff --git a/infra/security/telemetry.nginx.conf b/infra/security/telemetry.nginx.conf new file mode 100644 index 00000000..483870e1 --- /dev/null +++ b/infra/security/telemetry.nginx.conf @@ -0,0 +1,84 @@ +pid /tmp/nginx.pid; +events { worker_connections 512; } + +http { + access_log off; + server_tokens off; + client_body_temp_path /tmp/nginx-body; + proxy_temp_path /tmp/nginx-proxy; + fastcgi_temp_path /tmp/nginx-fastcgi; + uwsgi_temp_path /tmp/nginx-uwsgi; + scgi_temp_path /tmp/nginx-scgi; + client_max_body_size 16m; + + server { + listen 8444 ssl; + ssl_certificate /run/identity/server.crt; + ssl_certificate_key /run/identity/server.key; + ssl_protocols TLSv1.2 TLSv1.3; + proxy_set_header Authorization ""; + + location ~ ^/ingest/v1/(logs|metrics|traces)$ { + auth_basic "otlp-ingest"; + auth_basic_user_file /run/identity/ingest.htpasswd; + limit_except POST { deny all; } + rewrite ^/ingest(.*)$ $1 break; + proxy_pass http://127.0.0.1:14318; + } + location = /loki-write { + auth_basic "loki-write"; + auth_basic_user_file /run/identity/collector.htpasswd; + limit_except POST { deny all; } + proxy_pass http://127.0.0.1:3100/otlp/v1/logs; + } + location = /tempo-write { + auth_basic "tempo-write"; + auth_basic_user_file /run/identity/collector.htpasswd; + limit_except POST { deny all; } + proxy_pass http://127.0.0.1:14319/v1/traces; + } + location = /metrics { + auth_basic "prometheus-scrape"; + auth_basic_user_file /run/identity/scrape.htpasswd; + limit_except GET { deny all; } + proxy_pass http://127.0.0.1:8889/metrics; + } + location = /collector-metrics { + auth_basic "prometheus-scrape"; + auth_basic_user_file /run/identity/scrape.htpasswd; + limit_except GET { deny all; } + proxy_pass http://127.0.0.1:8888/metrics; + } + location /prometheus/api/v1/ { + auth_basic "grafana"; + auth_basic_user_file /run/identity/grafana.htpasswd; + limit_except GET POST { deny all; } + proxy_pass http://127.0.0.1:9090/api/v1/; + } + location /loki/loki/api/v1/ { + auth_basic "grafana"; + auth_basic_user_file /run/identity/grafana.htpasswd; + limit_except GET { deny all; } + proxy_pass http://127.0.0.1:3100/loki/api/v1/; + } + location /tempo/api/ { + auth_basic "grafana"; + auth_basic_user_file /run/identity/grafana.htpasswd; + limit_except GET { deny all; } + proxy_pass http://127.0.0.1:3200/api/; + } + location / { return 404; } + } + + server { + listen 3443 ssl; + ssl_certificate /run/identity/server.crt; + ssl_certificate_key /run/identity/server.key; + ssl_protocols TLSv1.2 TLSv1.3; + location / { + proxy_set_header Host $http_host; + proxy_set_header X-Forwarded-Proto https; + proxy_pass http://127.0.0.1:3000; + } + } +} diff --git a/infra/tempo/tempo.yml b/infra/tempo/tempo.yml new file mode 100644 index 00000000..00aa9f42 --- /dev/null +++ b/infra/tempo/tempo.yml @@ -0,0 +1,28 @@ +server: + http_listen_address: 127.0.0.1 + grpc_listen_address: 127.0.0.1 + http_listen_port: 3200 + +distributor: + receivers: + otlp: + protocols: + http: + endpoint: 127.0.0.1:14319 + +ingester: + max_block_duration: 5m + +compactor: + compaction: + block_retention: 168h + +storage: + trace: + backend: local + + wal: + path: /var/tempo/wal + + local: + path: /var/tempo/blocks diff --git a/nginx/nginx.conf b/nginx/nginx.conf new file mode 100644 index 00000000..9380361c --- /dev/null +++ b/nginx/nginx.conf @@ -0,0 +1,58 @@ +pid /tmp/nginx.pid; +events { worker_connections 512; } + +http { + access_log off; + server_tokens off; + client_body_temp_path /tmp/nginx-body; + proxy_temp_path /tmp/nginx-proxy; + fastcgi_temp_path /tmp/nginx-fastcgi; + uwsgi_temp_path /tmp/nginx-uwsgi; + scgi_temp_path /tmp/nginx-scgi; + + limit_req_zone $binary_remote_addr zone=logins:1m rate=2r/s; + + upstream api_backend { + zone api_backend 64k; + resolver 127.0.0.11 valid=5s ipv6=off; + least_conn; + server app1:8443 resolve max_fails=1 fail_timeout=5s; + server app2:8443 resolve max_fails=1 fail_timeout=5s; + } + + server { + listen 8443 ssl; + ssl_certificate /run/identity/server.crt; + ssl_certificate_key /run/identity/server.key; + ssl_protocols TLSv1.2 TLSv1.3; + client_max_body_size 10m; + + proxy_ssl_certificate /run/identity/lb.crt; + proxy_ssl_certificate_key /run/identity/lb.key; + proxy_ssl_trusted_certificate /run/ca/ca.crt; + proxy_ssl_verify on; + proxy_ssl_server_name on; + proxy_ssl_name api.internal; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For ""; + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_connect_timeout 2s; + proxy_read_timeout 10s; + + location = /api/v1/auth/sessions { + limit_req zone=logins burst=12 nodelay; + limit_req_status 429; + error_page 429 = @rate_limited; + proxy_pass https://api_backend; + } + location @rate_limited { + default_type application/json; + add_header Retry-After 1 always; + add_header X-Request-Id $request_id always; + return 429 '{"error":{"code":"rate_limited","message":"Too many login requests","request_id":"$request_id"}}'; + } + location / { + proxy_pass https://api_backend; + } + } +} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..c4637b20 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,18 @@ +fastapi==0.115.0 +uvicorn[standard]==0.52.4 +pydantic==2.13.5 +asyncpg==0.31.0 +sqlalchemy[asyncio]==2.1.0 +redis==6.2.0 +argon2-cffi==25.1.0 +bcrypt==4.1.2 +alembic==1.14.0 +psycopg2-binary +filetype==1.2.0 +Pillow==10.4.0 +minio==7.2.9 +python-multipart==0.0.9 +aio-pika==9.4.0 +opentelemetry-api==1.32.0 +opentelemetry-sdk==1.32.0 +opentelemetry-exporter-otlp-proto-http==1.32.0 \ No newline at end of file diff --git a/schemas/__init__.py b/schemas/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/schemas/chat.py b/schemas/chat.py new file mode 100644 index 00000000..97786751 --- /dev/null +++ b/schemas/chat.py @@ -0,0 +1,14 @@ +from pydantic import BaseModel, Field, field_validator, ConfigDict + + +class CreateChat(BaseModel): + model_config = ConfigDict(extra="forbid") + title: str = Field(min_length=1, max_length=100) + member_ids: list[str] = Field(min_length=1, max_length=100) + + @field_validator("member_ids") + @classmethod + def unique_members(cls, v): + if len(set(v)) != len(v): + raise ValueError("member_ids должны быть уникальными") + return v \ No newline at end of file diff --git a/schemas/message.py b/schemas/message.py new file mode 100644 index 00000000..6e8830b5 --- /dev/null +++ b/schemas/message.py @@ -0,0 +1,6 @@ +from pydantic import BaseModel, Field, ConfigDict + + +class CreateMessage(BaseModel): + model_config = ConfigDict(extra="forbid") + text: str = Field(min_length=1, max_length=4000) \ No newline at end of file diff --git a/schemas/user.py b/schemas/user.py new file mode 100644 index 00000000..81888ef1 --- /dev/null +++ b/schemas/user.py @@ -0,0 +1,7 @@ +from pydantic import BaseModel, Field, ConfigDict + + +class CreateUser(BaseModel): + model_config = ConfigDict(extra="forbid") + username: str = Field(pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(min_length=1, max_length=100) \ No newline at end of file diff --git a/scripts/__init__.py b/scripts/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/scripts/bench_password.py b/scripts/bench_password.py new file mode 100644 index 00000000..b3cc5934 --- /dev/null +++ b/scripts/bench_password.py @@ -0,0 +1,23 @@ +"""Measure Argon2id hashing and verification inside the constrained app image.""" +from statistics import median, quantiles +from time import perf_counter + +from app.security import pwd_context + + +def main(): + password = "Synthetic Argon2 measurement sample" + digest = pwd_context.hash(password) + for name, operation in (("hash", lambda: pwd_context.hash(password)), + ("verify", lambda: pwd_context.verify(digest, password))): + samples = [] + for _ in range(40): + start = perf_counter() + operation() + samples.append(1000 * (perf_counter() - start)) + print(f"{name}: n={len(samples)}, p50={median(samples):.2f} ms, " + f"p95={quantiles(samples, n=20)[18]:.2f} ms") + + +if __name__ == "__main__": + main() diff --git a/scripts/check_telemetry.py b/scripts/check_telemetry.py new file mode 100644 index 00000000..edc31c88 --- /dev/null +++ b/scripts/check_telemetry.py @@ -0,0 +1,52 @@ +"""Verify the provisioned Grafana data sources through authenticated HTTPS.""" +import base64 +import json +import os +from pathlib import Path +import ssl +import time +from urllib.parse import urlencode +from urllib.request import Request, urlopen + +ROOT = Path(__file__).resolve().parents[1] +STATE = Path(os.environ.get("LAB7_STATE", ROOT / "secrets/lab7")) +ADDRESS = f"https://localhost:{os.environ.get('GRAFANA_HTTPS_PORT', '3443')}" +METRICS = ( + "http_requests_total", "http_request_duration_seconds_bucket", + "jobs_processed_total", "job_processing_duration_seconds_bucket", +) + + +def main(): + context = ssl.create_default_context(cafile=str(STATE / "ca/ca.crt")) + password = (STATE / "grafana/admin/admin_password").read_text().strip() + credentials = base64.b64encode(f"admin:{password}".encode()).decode() + + def get(path, **params): + uri = ADDRESS + path + ("?" + urlencode(params) if params else "") + req = Request(uri, headers={"Authorization": "Basic " + credentials}) + with urlopen(req, context=context, timeout=6) as response: + return json.load(response) + + prefix = "/api/datasources/proxy/uid/" + assert get("/api/health")["database"] == "ok" + for _ in range(10): + if all(get(prefix + "prometheus/api/v1/query", query=metric)["data"]["result"] + for metric in METRICS): + break + time.sleep(3) + else: + raise AssertionError("Prometheus has not received all four metrics; run HTTPS smoke first") + print("PASS Grafana → Prometheus: API and worker counters and histograms") + + for service in ("messenger-api", "messenger-worker"): + streams = get(prefix + "loki/loki/api/v1/query_range", + query='{service_name="' + service + '"}', limit=50)["data"]["result"] + trace_id = next(item["stream"]["trace_id"] for item in streams if item["stream"].get("trace_id")) + trace = get(prefix + "tempo/api/traces/" + trace_id) + assert trace.get("batches") or trace.get("resourceSpans"), service + print(f"PASS Grafana → Loki → Tempo: {service}") + + +if __name__ == "__main__": + main() diff --git a/scripts/failover-test.sh b/scripts/failover-test.sh new file mode 100755 index 00000000..e7b7b199 --- /dev/null +++ b/scripts/failover-test.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +REPLICA="${1:-app1}" + +echo "Останавливаю $REPLICA" +date +"%H:%M:%S.%3N" +./scripts/stop-one.sh "$REPLICA" + +echo "" +echo "Шлю запросы каждые 0.5 сек, смотрю код и x-instance-id" +for i in {1..20}; do + TS=$(date +"%H:%M:%S.%3N") + CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/health/live) + INST=$(curl -s -i http://localhost:8080/health/live | grep -i "^x-instance-id:" | tr -d '\r') + echo "$TS code=$CODE $INST" + sleep 0.5 +done + +echo "" +echo "Поднимаю $REPLICA обратно" +docker compose start "$REPLICA" \ No newline at end of file diff --git a/scripts/lab7.py b/scripts/lab7.py new file mode 100644 index 00000000..2988de89 --- /dev/null +++ b/scripts/lab7.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +"""Operator bootstrap for the local Compose stand.""" +import argparse +import base64 +import hashlib +import json +import os +from pathlib import Path +import secrets +import ssl +import subprocess +import sys +import time +from urllib.error import HTTPError, URLError + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from app.bao import request + +STATE = Path(os.environ.get("LAB7_STATE", ROOT / "secrets/lab7")).resolve() +PRIVATE = STATE / "operator" +ADDRESS = f"https://localhost:{os.environ.get('BAO_HOST_PORT', '8200')}" +ROLES = {"api": ("app1", "app2"), "worker": ("worker",), + "outbox": ("outbox",), "migrate": ("migrate",)} +S3_BUCKET = "messenger-attachments" + + +def write(path, value, mode=0o444): + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + with temporary.open("x") as handle: + handle.write(value) + handle.flush() + os.fsync(handle.fileno()) + temporary.chmod(mode) + temporary.replace(path) + + +def save(path, data, mode=0o444): + write(path, json.dumps(data, indent=2) + "\n", mode) + + +def compose(*args, **kwargs): + env = {**os.environ, "LAB7_STATE": str(STATE)} + return subprocess.run(["docker", "compose", *args], cwd=ROOT, env=env, check=True, **kwargs) + + +def openssl(*args, payload=None): + run = subprocess.run(["openssl", *map(str, args)], input=payload, text=True, capture_output=True) + if run.returncode: + raise RuntimeError(f"OpenSSL {args[0]} failed: {run.stderr}") + return run.stdout.strip() + + +def ca(name): + key, cert = (PRIVATE / f"{name}.{ext}" for ext in ("key", "crt")) + openssl("req", "-x509", "-newkey", "rsa:3072", "-nodes", "-days", "365", + "-subj", f"/CN={name}", "-addext", "basicConstraints=critical,CA:TRUE", + "-addext", "keyUsage=critical,keyCertSign,cRLSign", "-keyout", key, "-out", cert) + key.chmod(0o600) + return key, cert + + +def leaf(path, name, san, usage, issuer): + path.parent.mkdir(parents=True, exist_ok=True) + key, cert = path.with_suffix(".key"), path.with_suffix(".crt") + csr, ext = PRIVATE / "leaf.csr", PRIVATE / "leaf.ext" + try: + openssl("req", "-new", "-newkey", "rsa:2048", "-nodes", "-subj", "/CN=" + name, + "-keyout", key, "-out", csr) + ext.write_text(f"subjectAltName={san}\nextendedKeyUsage={usage}\n" + "basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\n") + openssl("x509", "-req", "-in", csr, "-CA", issuer[1], "-CAkey", issuer[0], + "-set_serial", "0x" + secrets.token_hex(18), "-days", "90", + "-sha256", "-extfile", ext, "-out", cert) + finally: + csr.unlink(missing_ok=True) + ext.unlink(missing_ok=True) + key.chmod(0o444) + cert.chmod(0o444) + + +def certs(): + issuer = ca("lab7-root") + foreign = ca("lab7-test-foreign") + write(STATE / "ca/ca.crt", issuer[1].read_text()) + for name in ("app1", "app2", "nginx", "db", "redis", "rabbitmq", "minio", "openbao", "telemetry"): + san = f"DNS:{name}" + if name in ("app1", "app2"): + san += ",DNS:api.internal" + if name in ("nginx", "openbao", "telemetry"): + san += ",DNS:localhost,IP:127.0.0.1" + path = STATE / name / "server" + if name == "minio": + leaf(path, name, san, "serverAuth", issuer) + path.with_suffix(".crt").rename(path.parent / "public.crt") + path.with_suffix(".key").rename(path.parent / "private.key") + else: + leaf(path, name, san, "serverAuth", issuer) + leaf(STATE / "nginx/lb", "lab7-lb", "URI:spiffe://lab7/ingress", "clientAuth", issuer) + leaf(STATE / "verify/wrong-role", "lab7-other", "URI:spiffe://lab7/other", "clientAuth", issuer) + leaf(STATE / "verify/wrong-ca", "lab7-lb", "URI:spiffe://lab7/ingress", "clientAuth", foreign) + for ext in ("crt", "key"): + write(STATE / f"verify/lb.{ext}", (STATE / f"nginx/lb.{ext}").read_text()) + + +def file_password(directory, name, value): + write(STATE / directory / name, value + "\n") + + +def app_secret_config(passwords): + def database(role): + return f"postgresql+asyncpg://messenger_{role}:{passwords['db_' + role]}@db:5432/messenger_db" + + configs = {role: {"DATABASE_URL": database(role)} for role in ROLES} + configs["api"]["REDIS_URL"] = f"rediss://api:{passwords['redis']}@redis:6380/0" + for role in ("api", "worker"): + configs[role].update(S3_ACCESS_KEY_ID=f"messenger-{role}", S3_SECRET_ACCESS_KEY=passwords["s3_" + role], + OTEL_USERNAME=role, OTEL_PASSWORD=passwords["otel_" + role]) + for role in ("worker", "outbox"): + configs[role]["RABBITMQ_URL"] = f"amqps://{role}:{passwords['rabbit_' + role]}@rabbitmq:5671/jobs" + return configs + + +def configure_s3(passwords): + for directory in ("minio", "minio-init"): + file_password(directory, "admin_password", passwords["s3_admin"]) + for role, prefixes in (("api", ["originals"]), ("worker", ["thumbnails", "crops", "webp"])): + file_password("minio-init", f"{role}_password", passwords["s3_" + role]) + resource = f"arn:aws:s3:::{S3_BUCKET}" + save(STATE / f"minio-init/{role}_policy.json", { + "Version": "2012-10-17", + "Statement": [ + {"Effect": "Allow", "Action": ["s3:GetBucketLocation"], "Resource": [resource]}, + {"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": [resource + "/*"]}, + {"Effect": "Allow", "Action": ["s3:PutObject"], + "Resource": [f"{resource}/{prefix}/*" for prefix in prefixes]}, + ], + }) + + +def configure_rabbit(passwords): + users, permissions = [], [] + for role in ("worker", "outbox"): + salt = secrets.token_bytes(4) + digest = hashlib.sha256(salt + passwords["rabbit_" + role].encode()).digest() + users.append({"name": role, "password_hash": base64.b64encode(salt + digest).decode(), + "hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []}) + permissions.append({"user": role, "vhost": "jobs", "configure": "^image_tasks$", + "write": r"^amq\.default$", "read": "^image_tasks$" if role == "worker" else "^$"}) + save(STATE / "rabbitmq/definitions.json", {"users": users, "vhosts": [{"name": "jobs"}], + "permissions": permissions}) + + +def configure_telemetry(passwords): + def password_file(name, users): + lines = [username + ":" + openssl("passwd", "-6", "-stdin", payload=password + "\n") + for username, password in users.items()] + write(STATE / "telemetry" / f"{name}.htpasswd", "\n".join(lines) + "\n") + + password_file("ingest", {role: passwords["otel_" + role] for role in ("api", "worker")}) + password_file("collector", {"collector": passwords["otel_write"]}) + password_file("scrape", {"prometheus": passwords["otel_scrape"]}) + password_file("grafana", {"grafana": passwords["otel_query"]}) + file_password("grafana/admin", "admin_password", passwords["grafana"]) + file_password("prometheus", "scrape_password", passwords["otel_scrape"]) + save(STATE / "collector/collector.json", {"extensions": { + "basicauth/collector": {"client_auth": {"password": passwords["otel_write"]}} + }}) + ca_cert = (STATE / "ca/ca.crt").read_text() + template = ROOT / "infra/grafana/provisioning/datasources/datasources.yml" + provisioning = json.loads(template.read_text()) + for source in provisioning["datasources"]: + source["secureJsonData"] = {"tlsCACert": ca_cert, + "basicAuthPassword": passwords["otel_query"]} + save(STATE / "grafana/datasources/datasources.yaml", provisioning) + + +def prepare(): + marker = PRIVATE / "passwords.json" + if marker.is_file(): + return json.loads(marker.read_text()) + if STATE.exists() and any(STATE.iterdir()): + raise RuntimeError(f"Incomplete local bootstrap at {STATE}; inspect it before reusing") + STATE.mkdir(parents=True, exist_ok=True) + STATE.chmod(0o700) + PRIVATE.mkdir(mode=0o700) + certs() + passwords = {key: secrets.token_hex(24) for key in + ("db_admin", "db_api", "db_worker", "db_outbox", "db_migrate", "redis", "s3_admin", + "s3_api", "s3_worker", "rabbit_worker", "rabbit_outbox", "otel_api", "otel_worker", + "otel_write", "otel_scrape", "otel_query", "grafana")} + file_password("db", "admin_password", passwords["db_admin"]) + write(STATE / "redis/users.acl", "user default off\n" + f"user api on >{passwords['redis']} ~session:* ~idem:* +ping +get +set +setex +del\n") + configure_s3(passwords) + configure_rabbit(passwords) + configure_telemetry(passwords) + for role, targets in ROLES.items(): + for target in targets: + (STATE / target).mkdir(exist_ok=True) + save(marker, passwords, mode=0o600) + return passwords + + +def configure_bao(passwords): + context = ssl.create_default_context(cafile=str(STATE / "ca/ca.crt")) + + def bao(path, data=None, token=None): + return request(ADDRESS, path, context=context, data=data, token=token) + + for _ in range(60): + try: + init = bao("sys/init") + break + except (URLError, TimeoutError): + time.sleep(1) + else: + raise RuntimeError("OpenBao HTTPS listener unavailable") + operator = PRIVATE / "openbao.json" + if not init["initialized"]: + if operator.exists(): + raise RuntimeError("OpenBao volume and operator shares mismatch") + save(operator, bao("sys/init", {"secret_shares": 3, "secret_threshold": 2}), 0o600) + state = json.loads(operator.read_text()) + if bao("sys/seal-status")["sealed"]: + for share in state["keys_base64"][:2]: + bao("sys/unseal", {"key": share}) + token = state["root_token"] + + if "messenger/" not in bao("sys/mounts", token=token): + bao("sys/mounts/messenger", {"type": "kv", "options": {"version": "2"}}, token) + if "approle/" not in bao("sys/auth", token=token): + bao("sys/auth/approle", {"type": "approle"}, token) + for role, data in app_secret_config(passwords).items(): + policy = (ROOT / "infra/openbao/service-policy.hcl").read_text().replace("ROLE_NAME", role) + bao(f"sys/policies/acl/messenger-{role}", {"policy": policy}, token) + bao(f"messenger/data/{role}", {"data": data}, token) + base = f"auth/approle/role/{role}" + bao(base, {"token_policies": [f"messenger-{role}"], "token_ttl": "5m", + "token_max_ttl": "5m", "secret_id_ttl": "720h"}, token) + role_id = bao(base + "/role-id", token=token)["data"]["role_id"] + for target in (*ROLES[role], *(("verify/" + role,) if role in ("api", "worker") else ())): + sid = bao(base + "/secret-id", {}, token)["data"]["secret_id"] + write(STATE / target / "role_id", role_id + "\n") + write(STATE / target / "secret_id", sid + "\n") + + +def unseal(): + state = json.loads((PRIVATE / "openbao.json").read_text()) + context = ssl.create_default_context(cafile=str(STATE / "ca/ca.crt")) + for _ in range(20): + try: + if not request(ADDRESS, "sys/seal-status", context=context)["sealed"]: + return + break + except (URLError, TimeoutError): + time.sleep(0.5) + for share in state["keys_base64"][:2]: + request(ADDRESS, "sys/unseal", context=context, data={"key": share}) + print("OpenBao unsealed") + + +def psql(sql): + compose("exec", "-T", "db", "psql", "-X", "-q", "--set=ON_ERROR_STOP=1", "-U", + "messenger_admin", "-d", "messenger_db", input=sql, text=True) + + +def provision_database(passwords): + fragments = ["REVOKE CREATE ON SCHEMA public FROM PUBLIC;"] + for role in ROLES: + name = f"messenger_{role}" + fragments.append(f"""DO $$ BEGIN + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '{name}') THEN + CREATE ROLE {name} LOGIN; + END IF; + END $$; + ALTER ROLE {name} PASSWORD '{passwords['db_' + role]}'; + GRANT CONNECT ON DATABASE messenger_db TO {name}; + GRANT USAGE ON SCHEMA public TO {name};""") + fragments.append("GRANT CREATE ON SCHEMA public TO messenger_migrate;") + psql("\n".join(fragments)) + + +def start(): + passwords = prepare() + compose("up", "-d", "db", "redis", "rabbitmq", "minio", "openbao", + "telemetry", "otel-collector", "prometheus", "loki", "tempo", "grafana") + configure_bao(passwords) + compose("run", "--rm", "--no-deps", "minio-init") + for _ in range(30): + check = subprocess.run(["docker", "compose", "exec", "-T", "db", "pg_isready", + "-h", "127.0.0.1", "-U", "messenger_admin", "-d", "messenger_db"], + cwd=ROOT, env={**os.environ, "LAB7_STATE": str(STATE)}, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + if check.returncode == 0: + break + time.sleep(1) + else: + raise RuntimeError("PostgreSQL unavailable") + provision_database(passwords) + compose("build", "app1") + compose("run", "--rm", "--no-deps", "migrate") + psql((ROOT / "infra/security/database-grants.sql").read_text()) + compose("up", "-d", "--no-build", "app1", "app2", "worker", "outbox", "nginx") + print(f"CA: {STATE / 'ca/ca.crt'}") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=["up", "unseal"]) + if parser.parse_args().command == "up": + start() + else: + unseal() + + +if __name__ == "__main__": + try: + main() + except (HTTPError, subprocess.CalledProcessError, RuntimeError) as error: + sys.exit(f"Bootstrap: {error}") diff --git a/scripts/ram-experiment.py b/scripts/ram-experiment.py new file mode 100644 index 00000000..ea6525c9 --- /dev/null +++ b/scripts/ram-experiment.py @@ -0,0 +1,90 @@ +import io +import os +import time +import uuid +import requests +from concurrent.futures import ThreadPoolExecutor +from PIL import Image + +BASE_URL = "http://localhost:8080" +CONCURRENCY = 10 + + +def make_png(width, height): + img = Image.frombytes('RGB', (width, height), os.urandom(width * height * 3)) + buf = io.BytesIO() + img.save(buf, format='PNG', optimize=False) + return buf.getvalue() + + +def register_and_login(username): + requests.post(f"{BASE_URL}/api/v1/users", json={ + "username": username, "display_name": "Test", "password": "valid_password_123" + }) + resp = requests.post(f"{BASE_URL}/api/v1/auth/sessions", + auth=(username, "valid_password_123")) + return resp.json()["token"] + + +def create_chat(token): + headers = {"Authorization": f"Bearer {token}"} + me = requests.get(f"{BASE_URL}/api/v1/users/me", headers=headers).json() + resp = requests.post(f"{BASE_URL}/api/v1/chats", headers=headers, json={ + "title": "RAM Test", "member_ids": [me["id"]] + }) + return resp.json()["id"] + + +def upload(token, chat_id, content, filename): + headers = {"Authorization": f"Bearer {token}", "Content-Type": "image/png"} + start = time.monotonic() + resp = requests.post( + f"{BASE_URL}/api/v1/chats/{chat_id}/attachments?filename={filename}", + headers=headers, data=content, timeout=60, + ) + elapsed = time.monotonic() - start + return resp.status_code, elapsed, len(content) + + +def main(): + print(f"RAM Experiment: {CONCURRENCY} concurrent uploads, ~5 MB each") + token = register_and_login("ram_tester") + chat_id = create_chat(token) + print(f"Chat ID: {chat_id}") + + print(f"Генерируем {CONCURRENCY} картинок (шум, ~5 МБ)...") + contents = [make_png(1400 + i * 20, 1400 + i * 20) for i in range(CONCURRENCY)] + sizes = [len(c) / (1024 * 1024) for c in contents] + print(f"Размеры: min={min(sizes):.2f}, max={max(sizes):.2f}, avg={sum(sizes)/len(sizes):.2f} МБ") + print(f"Суммарно: {sum(sizes):.2f} МБ") + + print(f"\nЗапускаем {CONCURRENCY} одновременных загрузок...") + start = time.monotonic() + results, errors = [], [] + + with ThreadPoolExecutor(max_workers=CONCURRENCY) as pool: + futures = [ + pool.submit(upload, token, chat_id, contents[i], f"ram-{i}-{uuid.uuid4().hex[:8]}.png") + for i in range(CONCURRENCY) + ] + for f in futures: + try: + results.append(f.result()) + except Exception as e: + errors.append(str(e)) + + total = time.monotonic() - start + print(f"\n=== Результаты ===") + print(f"Всего: {len(results) + len(errors)}") + print(f"Успешных (201): {sum(1 for r in results if r[0] == 201)}") + print(f"Ошибок: {len(errors)}") + if results: + lat = [r[1] for r in results] + print(f"Latency: min={min(lat):.2f}s, max={max(lat):.2f}s, avg={sum(lat)/len(lat):.2f}s") + print(f"Общее время: {total:.2f}s") + if errors: + print(f"Ошибки: {errors[:5]}") + + +if __name__ == "__main__": + main() diff --git a/scripts/reconcile.py b/scripts/reconcile.py new file mode 100644 index 00000000..df04f481 --- /dev/null +++ b/scripts/reconcile.py @@ -0,0 +1,147 @@ +import argparse +import asyncio +from datetime import datetime, timedelta, timezone +from minio import Minio +from app.transport import s3_transport +from sqlalchemy import select, cast, Text +from app.models.chat import Chat, ChatMember +from app.models.user import User +from app.models.message import Message +from app.database import async_session_maker +from app.models.attachment import Attachment +from app.config import ( + S3_ENDPOINT, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_BUCKET +) + +GRACE_PERIOD = timedelta(seconds=1) + + +endpoint = S3_ENDPOINT.replace("http://", "").replace("https://", "") +minio_client = Minio( + endpoint, + access_key=S3_ACCESS_KEY_ID, + secret_key=S3_SECRET_ACCESS_KEY, + **s3_transport(S3_ENDPOINT), +) +BUCKET = S3_BUCKET + + +async def find_orphan_s3_objects(dry_run: bool) -> int: + print("Поиск orphan объектов в S3, файлы без записи в БД") + + async with async_session_maker() as session: + result = await session.execute(select(Attachment.object_key)) + db_keys = {row[0] for row in result.all()} + + print(f"Файлов в БД: {len(db_keys)}") + + objects = list(minio_client.list_objects(BUCKET, recursive=True)) + print(f"Объектов в MinIO: {len(objects)}") + + now = datetime.now(timezone.utc) + orphans = [] + + for obj in objects: + if obj.object_name not in db_keys: + age = now - obj.last_modified if obj.last_modified else timedelta(0) + if age > GRACE_PERIOD: + orphans.append(obj.object_name) + print(f" [ORPHAN] {obj.object_name} (возраст: {age}, старше grace_period)") + else: + print(f" [SKIP] {obj.object_name} (возраст: {age} — свежий, не трогаем)") + + if not orphans: + print("Orphan-объектов не найдено.") + return 0 + + if dry_run: + print(f"[DRY-RUN] Найдено {len(orphans)} orphan. Удаление не выполнено.") + else: + for key in orphans: + minio_client.remove_object(BUCKET, key) + print(f" [DELETED] {key}") + print(f"Удалено {len(orphans)} orphan-объектов.") + + return len(orphans) + + +async def find_missing_s3_objects(dry_run: bool) -> int: + print("\nПоиск missing объектов, записи в БД без файла в MinIO") + + async with async_session_maker() as session: + result = await session.execute(select(Attachment.id, Attachment.object_key)) + attachments = result.all() + + print(f"Записей в БД: {len(attachments)}") + + missing = [] + used_missing = [] + + for att_id, key in attachments: + try: + minio_client.stat_object(BUCKET, key) + except Exception: + + async with async_session_maker() as session: + result_msg = await session.execute( + select(Message).where( + cast(Message.attachment_ids, Text).contains(f'"{att_id}"') + ) + ) + is_used = result_msg.scalar_one_or_none() is not None + + if is_used: + used_missing.append((att_id, key)) + print(f" [SKIP] id={att_id}, key={key} — используется в сообщении, не удаляем") + else: + missing.append((att_id, key)) + print(f" [MISSING] id={att_id}, key={key} — не используется, можно удалить") + + total = len(missing) + len(used_missing) + if total == 0: + print("Missing-записей не найдено.") + return 0 + + if dry_run: + print(f"[DRY-RUN] Missing: {len(missing)} (удалить), {len(used_missing)} (используется, SKIP). Удаление не выполнено.") + else: + if missing: + async with async_session_maker() as session: + for att_id, _ in missing: + att = await session.get(Attachment, att_id) + if att: + await session.delete(att) + await session.commit() + print(f"Удалено {len(missing)} неиспользуемых missing из БД.") + if used_missing: + print(f" [SKIP] {len(used_missing)} используемых missing — не удалены (защита от битых сообщений).") + + return len(missing) + + +async def main(): + parser = argparse.ArgumentParser(description="Reconciler: чистка S3/БД") + parser.add_argument("--dry-run", action="store_true", help="Только показать, не удалять") + parser.add_argument("--execute", action="store_true", help="Удалить найденное") + args = parser.parse_args() + + if not args.dry_run and not args.execute: + print("Укажите --dry-run или --execute") + return + + dry_run = args.dry_run and not args.execute + + orphans = await find_orphan_s3_objects(dry_run) + missing = await find_missing_s3_objects(dry_run) + + print("\nИтог") + print(f"Orphan S3 без БД: {orphans}") + print(f"Missing БД без S3 (удалено): {missing}") + if dry_run: + print("Режим: DRY-RUN (ничего не удалено)") + else: + print("Режим: EXECUTE (изменения применены)") + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..de40b797 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu + +cd "$(dirname "$0")/.." +docker compose stop nginx app1 app2 worker outbox +docker compose restart db redis minio rabbitmq openbao +python3 scripts/lab7.py unseal +docker compose up -d --no-build nginx app1 app2 worker outbox diff --git a/scripts/rolling-load.sh b/scripts/rolling-load.sh new file mode 100755 index 00000000..5b4a862c --- /dev/null +++ b/scripts/rolling-load.sh @@ -0,0 +1,12 @@ + +echo "Нагрузка: 30 запросов с интервалом 0.5 сек" +for i in {1..30}; do + TS=$(date +"%H:%M:%S") + + RESP=$(curl -s -i http://localhost:8080/health/live) + CODE=$(echo "$RESP" | head -1 | awk '{print $2}') + INST=$(echo "$RESP" | grep -i "^x-instance-id:" | tr -d '\r' | awk '{print $2}') + + echo "$TS code=$CODE instance=${INST:-<нет>}" + sleep 0.5 +done \ No newline at end of file diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh new file mode 100755 index 00000000..89b1888e --- /dev/null +++ b/scripts/rolling-update.sh @@ -0,0 +1,20 @@ + +set -e + +echo "Rolling update: app1" +docker compose stop app1 +docker compose up -d --build app1 +echo "Жду, пока app1 станет healthy..." +sleep 5 + +echo "" +echo "Rolling update: app2" +docker compose stop app2 +docker compose up -d --build app2 +echo "Жду, пока app2 станет healthy..." +sleep 5 + +echo "" +echo "Проверка: обе реплики живы" +curl -i http://localhost:8080/health/live +curl -i http://localhost:8080/health/live \ No newline at end of file diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 00000000..fd057706 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,31 @@ +#!/bin/sh +set -eu + +cd "$(dirname "$0")/.." +case "${1:-}" in + app1|app2) + docker compose stop --timeout 3 "$1" + exit + ;; + "") + ;; + *) + printf '%s\n' 'Expected app1 or app2' >&2 + exit 2 + ;; +esac + +: "${TARGET_INSTANCE_ID:?Expected target API instance ID}" +for replica in app1 app2; do + headers=$(docker compose exec -T nginx curl -fsS --noproxy '*' --max-time 3 \ + --cacert /run/ca/ca.crt --cert /run/identity/lb.crt --key /run/identity/lb.key \ + --connect-to "api.internal:8443:$replica:8443" \ + -D - -o /dev/null https://api.internal:8443/health/live) + instance=$(printf '%s\n' "$headers" | awk 'tolower($1)=="x-instance-id:" {print $2}' | tr -d '\r') + if [ "$instance" = "$TARGET_INSTANCE_ID" ]; then + docker compose stop --timeout 3 "$replica" + exit + fi +done +printf '%s\n' 'Target API instance was not found' >&2 +exit 1 diff --git a/scripts/test-stream-limit.py b/scripts/test-stream-limit.py new file mode 100644 index 00000000..081a4aee --- /dev/null +++ b/scripts/test-stream-limit.py @@ -0,0 +1,61 @@ +import time +import requests + +BASE_URL = "http://localhost:8080" + + +def get_token(username="stream_tester"): + requests.post(f"{BASE_URL}/api/v1/users", json={ + "username": username, "display_name": "T", "password": "valid_password_123" + }) + resp = requests.post(f"{BASE_URL}/api/v1/auth/sessions", + auth=(username, "valid_password_123")) + return resp.json()["token"] + + +def get_chat(token): + headers = {"Authorization": f"Bearer {token}"} + me = requests.get(f"{BASE_URL}/api/v1/users/me", headers=headers).json() + resp = requests.post(f"{BASE_URL}/api/v1/chats", headers=headers, json={ + "title": "Stream Test", "member_ids": [me["id"]] + }) + return resp.json()["id"] + + +def main(): + print("=" * 60) + print(" STREAM LIMIT TEST") + print("=" * 60) + token = get_token() + chat_id = get_chat(token) + print(f"Chat ID: {chat_id}") + print("\n=== Отправляем 100 МБ чанками (ожидаем 413, без OOM) ===") + + def gen(): + for _ in range(100): + yield b"0" * (1024 * 1024) + + start = time.monotonic() + try: + resp = requests.post( + f"{BASE_URL}/api/v1/chats/{chat_id}/attachments?filename=big.png", + headers={"Authorization": f"Bearer {token}", "Content-Type": "image/png"}, + data=gen(), timeout=60, + ) + status = resp.status_code + except Exception as e: + print(f"Ошибка: {e}") + status = None + elapsed = time.monotonic() - start + print(f"Status: {status} (ожидаем 413)") + print(f"Время: {elapsed:.2f}s") + print("\n" + "=" * 60) + if status == 413: + print("PASS: потоковый лимит работает, 413") + else: + print(f"FAIL: ожидался 413, получен {status}") + print("=" * 60) + + +if __name__ == "__main__": + main() diff --git a/scripts/verify_lab7.py b/scripts/verify_lab7.py new file mode 100644 index 00000000..c91c0b7e --- /dev/null +++ b/scripts/verify_lab7.py @@ -0,0 +1,72 @@ +"""Defensive checks from inside the isolated lab7 network.""" +import http.client +import json +import os +from pathlib import Path +import ssl +from urllib.error import HTTPError + +from app.bao import CA_FILE, request, service_token + + +def check_mtls(): + for replica in ("app1", "app2"): + for certificate in ("lb", None, "wrong-ca", "wrong-role"): + context = ssl.create_default_context(cafile=CA_FILE) + if certificate: + base = "/run/identity/" + certificate + context.load_cert_chain(base + ".crt", base + ".key") + connection = http.client.HTTPSConnection(replica, 8443, context=context, timeout=4) + try: + connection.request("GET", "/health/live") + response = connection.getresponse() + accepted = response.status == 200 and json.loads(response.read()) == {"status": "ok"} + except (ssl.SSLError, http.client.RemoteDisconnected, ConnectionResetError, BrokenPipeError): + accepted = False + finally: + connection.close() + assert accepted == (certificate == "lb"), (replica, certificate) + print(f"PASS {replica}: correct LB certificate only") + + +def check_openbao(): + address = os.environ["BAO_ADDR"] + context = ssl.create_default_context(cafile=CA_FILE) + for role, other in (("api", "worker"), ("worker", "api")): + token = service_token(address, context, Path("/run/identity") / role) + try: + own = request(address, f"messenger/data/{role}", context=context, token=token) + keys = set(own["data"]["data"]) + assert {"DATABASE_URL", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"} <= keys, role + assert not keys & {"ROOT_TOKEN", "UNSEAL_KEY", "MINIO_ROOT_PASSWORD"} + for scope, body in ( + (f"messenger/data/{other}", None), + ("sys/policies/acl/lab7-probe", {"policy": ""}), + ): + try: + request(address, scope, context=context, token=token, data=body) + except HTTPError as exc: + assert exc.code == 403, (scope, exc.code) + else: + raise AssertionError(f"Unexpected access to {scope}") + finally: + request(address, "auth/token/revoke-self", context=context, token=token, data={}) + print(f"PASS OpenBao {role}: own secret allowed, cross-role read and policy write denied") + + +def check_ingest(): + context = ssl.create_default_context(cafile=CA_FILE) + connection = http.client.HTTPSConnection("telemetry", 8444, context=context, timeout=4) + try: + connection.request("POST", "/ingest/v1/metrics", body=b"") + with connection.getresponse() as response: + assert response.status == 401, response.status + finally: + connection.close() + print("PASS telemetry does not allow ingestion without service credentials") + + +if __name__ == "__main__": + check_mtls() + check_openbao() + check_ingest() diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 31da287d..3be3184e 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -1,19 +1,25 @@ -# Модель угроз — заполнить +# Модель угроз — lab7, уровень 3 ## Активы и акторы -TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. +Активы — пароли и сессии пользователей, история сообщений, вложения, служебные секреты, ключи TLS и телеметрия. Участник чата может работать только со своими чатами. Посторонний пользователь имеет обычную сессию и может отправлять HTTP-запросы. Сервис, оказавшийся под контролем постороннего, может пользоваться только своей идентичностью и доступными ему секретами. Оператор доверен. Доступ администратора к хосту и Docker даёт контроль над стендом и находится вне модели. ## Границы доверия -TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. +Публичный HTTPS заканчивается на Nginx. Каждая реплика FastAPI требует аутентификацию Nginx через mTLS. API отдельно проверяет Bearer и членство в чате. PostgreSQL, Redis, RabbitMQ, S3 и OpenBao принимают защищённые соединения. Группа наблюдаемости образует один локальный транспортный контур. К её TLS-шлюзу выдаются отдельные права записи, чтения и сбора метрик. Подробности и порты приведены в [матрице доверия](../contracts/trust-matrix.md). -| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | +| Угроза и путь | Что защищаем | Контроль | Проверка | Остаточное ограничение | | --- | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | TODO | +| Недоверенная сеть между клиентом и Nginx | Пароль, сессия и данные запроса | TLS с проверкой CA и имени сервера | `make test-security` и проверка чужого имени в `tests/grade3_api.py` | Хост доверенной стороны и локальный CA защищает оператор | +| Прямое подключение к API из сети Compose | Доступ к приложению только через разрешённый ingress | Нет опубликованного порта реплик. Обязательны подпись CA и URI SAN Nginx | Внутренний тест mTLS прогоняет четыре варианта на каждой реплике | Утечка закрытого ключа Nginx потребует замены сертификата | +| Посторонний читает или прикрепляет объект из чужого чата | Границы чата | Bearer, проверка членства и принадлежности вложения к чату | Публичный smoke и `tests/grade3_api.py` | Остаются доступы легитимных участников | +| Частые попытки входа и большие запросы | Доступность API | Лимит входа на Nginx по адресу соединения, лимит тела 10 MiB, два параллельных Argon2-вызова на реплику | `tests/grade3_api.py` получает 429 с Retry-After и 413 | Один IP за NAT делит общий лимит, распределённый трафик требует отдельной защиты | +| Повторное использование токена после выхода или истечения | Граница пользовательской сессии | Случайные Bearer, SHA-256 ключа в Redis, TTL и удаление при выходе | Публичный smoke проверяет logout, дополнительный тест проверяет TTL | Действующий украденный токен остаётся Bearer до выхода или истечения | +| Сервис запрашивает чужие секреты или изменяет политику | Раздельные идентичности и права сервисов | AppRole, отдельный путь KV и токен на 5 минут | Тест политик OpenBao проверяет 403 для чужого пути и записи политики | Сервис может читать свой набор секретов. Их смена требует операторской процедуры | +| Произвольный клиент отправляет данные телеметрии | Целостность сигналов | Только TLS-шлюз принимает OTLP. У каждой роли свой Basic-credential. HTTP-приёмники слушают loopback общей сетевой области | Проверка неавторизованной отправки и запрос через Grafana | Процессы внутри общей сетевой области считаются взаимно доверенными | -На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. +## Жизненный цикл и восстановление -## Lifecycle и инциденты +Оператор создаёт закрытые ключи и данные инициализации в каталоге с правами 0700. Доли разблокировки и root-токен имеют права 0600 и доступны только на хосте. Контейнер OpenBao хранит зашифрованные данные в именованном томе. У приложений отдельные файлы AppRole и публичный CA. Рабочий токен OpenBao отзывается сразу после чтения секретов. После обычного рестарта приложения выполняют новый вход. После рестарта самого OpenBao оператор выполняет `python3 scripts/lab7.py unseal`. -TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. +Сертификаты сервисов действуют 90 дней, CA — 365 дней, SecretID — 30 дней. Повторный запуск bootstrap выпускает новые SecretID для того же стенда. Используемые сервисами пароли на уровне 3 хранятся как отдельные KV-секреты и остаются в памяти процессов до перезапуска. При компрометации оператор останавливает затронутый сервис, отзывает его AppRole-идентичность, меняет рабочие credentials в целевой системе и OpenBao, затем запускает процесс с новыми данными. Автоматическую ротацию, отзыв leaf-сертификатов и аудит зависимостей под условия уровня 4 здесь не заявляем. diff --git a/tests/check_attachment_status.py b/tests/check_attachment_status.py new file mode 100644 index 00000000..756e0e61 --- /dev/null +++ b/tests/check_attachment_status.py @@ -0,0 +1,29 @@ + +import asyncio +import sys +from uuid import UUID + +from app.worker import async_session_maker, engine +from app.models.attachment import Attachment + + +async def main(): + attachment_id = UUID(sys.argv[1]) + + try: + async with async_session_maker() as session: + att = await session.get(Attachment, attachment_id) + + if att is None: + print("Attachment not found") + return + + print("Attachment ID:", att.id) + print("Status:", att.status) + print("Error code:", att.error_code) + finally: + await engine.dispose() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tests/grade3_api.py b/tests/grade3_api.py new file mode 100644 index 00000000..4520e5e8 --- /dev/null +++ b/tests/grade3_api.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Additional checks against the local lab7 HTTPS endpoint.""" +import base64 +import os +import time +import uuid +import socket +import ssl +from urllib.error import HTTPError +from urllib.parse import urlparse +from urllib.request import Request, urlopen + +from client import Client, arguments, check, run, timestamp +from datetime import datetime, timezone + + +def main(): + args = arguments("Verify lab7 login limit, body limit, foreign attachment, and optional session expiry", + lambda parser: parser.add_argument("--expiry-only", action="store_true")) + client = Client(args.base_url, args.ca_file) + if args.expiry_only: + username = "expiry_" + uuid.uuid4().hex[:12] + registration = {"username": username, "display_name": "Expiry", "password": "Пароль-" + uuid.uuid4().hex} + client.call("POST", "/api/v1/users", 201, body=registration) + auth = base64.b64encode(f"{username}:{registration['password']}".encode()).decode() + session = client.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + auth}, schema="Session")["json"] + actor = {"token": session["token"]} + client.call("GET", "/api/v1/users/me", actor=actor, schema="User") + until = (timestamp(session["expires_at"]) - datetime.now(timezone.utc)).total_seconds() + check(0 < until < 30, "run expiry verification on a stand using SESSION_TTL_SECONDS=8") + time.sleep(until + 0.6) + client.call("GET", "/api/v1/users/me", 401, actor=actor) + print("PASS HTTPS session works before TTL and returns 401 after expiry") + return + + context = ssl.create_default_context(cafile=args.ca_file or os.getenv('CA_FILE')) + address = urlparse(client.base) + try: + with socket.create_connection((address.hostname, address.port or 443), timeout=5) as conn: + with context.wrap_socket(conn, server_hostname="wrong-name.invalid"): + raise AssertionError("incorrect TLS hostname accepted") + except ssl.SSLCertVerificationError as exc: + check(exc.verify_code == 62, "expected hostname mismatch") + print("PASS HTTPS rejects an incorrect hostname with the trusted CA") + + alice, bob, eve, chat = client.bootstrap() + attachment, _ = client.attachment(alice, chat) + other_chat = client.call("POST", "/api/v1/chats", 201, actor=eve, + body={"title": "Another chat", "member_ids": [eve["id"], bob["id"]]}, + schema="Chat")["json"] + client.call("POST", f"/api/v1/chats/{other_chat['id']}/messages", (400, 404), + actor=eve, headers={"Idempotency-Key": uuid.uuid4().hex}, + body={"text": "Foreign attachment", "attachment_ids": [attachment["id"]]}) + print("PASS attachment cannot be linked into another chat") + + request = Request(client.base + "/api/v1/users", data=b"x" * (10 * 1024**2 + 1), method="POST") + try: + urlopen(request, context=context, timeout=10) + except HTTPError as exc: + check(exc.code == 413, "oversize body must return 413") + except BrokenPipeError: + raise AssertionError("oversize body response was not observed") from None + else: + raise AssertionError("oversize body was accepted") + print("PASS oversized body returns 413") + + auth = base64.b64encode(b"unknown-user:invalid-password").decode() + request = Request(client.base + "/api/v1/auth/sessions", method="POST", + headers={"Authorization": "Basic " + auth}) + for _ in range(25): + try: + urlopen(request, context=context, timeout=5) + except HTTPError as exc: + with exc: + check(exc.code in (401, 429), f"unexpected login status {exc.code}") + if exc.code == 429: + check(int(exc.headers.get("Retry-After", "0")) >= 1, "missing Retry-After") + print("PASS login limit returns 429 with Retry-After") + return + else: + raise AssertionError("login unexpectedly accepted") + raise AssertionError("login limiter did not activate") + + +if __name__ == "__main__": + run(main) diff --git a/tests/test_worker_retry.py b/tests/test_worker_retry.py new file mode 100644 index 00000000..79721279 --- /dev/null +++ b/tests/test_worker_retry.py @@ -0,0 +1,72 @@ +"""Verify retries with a synthetic missing object, using the local operator socket.""" +import os +from pathlib import Path +import subprocess +import time +import uuid + +from client import Client, arguments, check, run + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_CA = Path(os.environ.get("LAB7_STATE", ROOT / "secrets/lab7")) / "ca/ca.crt" + + +def sql(statement, **values): + arguments = [f"--set={key}={value}" for key, value in values.items()] + subprocess.run( + ["docker", "compose", "exec", "-T", "db", "psql", "-X", "-q", + "--set=ON_ERROR_STOP=1", "-U", "messenger_admin", "-d", "messenger_db", *arguments], + cwd=ROOT, input=statement, text=True, check=True, + ) + + +def verify(base_url=None, ca_file=None): + client = Client(base_url, ca_file or str(DEFAULT_CA)) + owner, _, _, chat = client.bootstrap() + fixture = { + "attachment_id": str(uuid.uuid4()), + "event_id": str(uuid.uuid4()), + "owner_id": str(uuid.UUID(owner["id"])), + "chat_id": str(uuid.UUID(chat["id"])), + } + sql( + """ + BEGIN; + INSERT INTO attachments (id, object_key, filename, mime_type, size_bytes, sha256, + chat_id, user_id, status, created_at, updated_at) + VALUES (:'attachment_id', 'originals/lab7-missing-' || :'attachment_id', 'missing.png', + 'image/png', 1, repeat('0', 64), :'chat_id', :'owner_id', 'queued', now(), now()); + INSERT INTO outbox_events (id, attachment_id) VALUES (:'event_id', :'attachment_id'); + COMMIT; + """, **fixture, + ) + try: + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + response = client.call("GET", f"/api/v1/attachments/{fixture['attachment_id']}", + actor=owner, schema="Attachment")["json"] + if response["status"] == "failed": + check(response["error_code"] == "s3_download_error", "incorrect worker error code") + print("PASS HTTPS worker retry reached failed with s3_download_error") + return + time.sleep(0.5) + raise AssertionError("worker did not reach failed within 60 seconds") + finally: + sql( + "BEGIN; DELETE FROM outbox_events WHERE attachment_id = :'attachment_id';" + " DELETE FROM attachments WHERE id = :'attachment_id'; COMMIT;", + attachment_id=fixture["attachment_id"], + ) + + +def test_worker_retry(): + verify() + + +def main(): + args = arguments("Verify worker retries on the local TLS-enabled compose stand") + verify(args.base_url, args.ca_file) + + +if __name__ == "__main__": + run(main)