diff --git a/.env.example b/.env.example index dcca2c61..65edd09c 100644 --- a/.env.example +++ b/.env.example @@ -32,6 +32,7 @@ MAX_JSON_BODY_BYTES=65536 SECRETS_REFRESH_SECONDS=15 # PostgreSQL: пул и таймауты. Роли api / worker / migrate, вход по сертификату + паролю из OpenBao. +DB_POOL_MIN=8 DB_POOL_MAX=10 DB_POOL_TIMEOUT=3 DB_STATEMENT_TIMEOUT_MS=5000 diff --git a/.gitattributes b/.gitattributes index 41fd68b9..27da93be 100644 --- a/.gitattributes +++ b/.gitattributes @@ -9,8 +9,8 @@ Dockerfile text eol=lf *.cmd text eol=crlf *.png binary *.jpg binary -*.conf text eol=lf -*.acl text eol=lf -*.hcl text eol=lf -*.yml text eol=lf -*.json text eol=lf +*.conf text eol=lf +*.acl text eol=lf +*.hcl text eol=lf +*.yml text eol=lf +*.json text eol=lf diff --git a/Dockerfile b/Dockerfile index bd16e9cc..8eb8e7a5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,7 +11,10 @@ RUN pip install --prefix=/install -r requirements.txt FROM python:3.12.7-slim-bookworm AS runtime ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 \ APP_HOST=0.0.0.0 APP_PORT=8443 HEALTH_PORT=8081 SHUTDOWN_TIMEOUT=10 -RUN useradd --create-home --uid 10001 appuser +# lab7 (scan triage): базовый образ закреплён, но пакеты Debian обновляем при сборке — +# закрывает исправленные в bookworm-security CVE (openssl, gnutls, perl, apt …). +RUN apt-get update && apt-get -y upgrade --no-install-recommends && rm -rf /var/lib/apt/lists/* \ + && useradd --create-home --uid 10001 appuser WORKDIR /app COPY --from=builder /install /usr/local COPY app ./app diff --git a/REPORT.md b/REPORT.md index ac8ac7be..24a8da55 100644 --- a/REPORT.md +++ b/REPORT.md @@ -110,7 +110,7 @@ docker compose --env-file .env down -v | `app/db.py` | `verify-full` + клиентский сертификат роли. Пароль из secretstore: пробуется текущий, затем предыдущий, затем `force_refresh` | | `app/ratelimit.py` | Общий лимит входа в Redis (pipeline INCR + EXPIRE NX + TTL), локальный запасной вариант | | `app/security.py` | Argon2id из настроек; ниже m=19456, t=2, p=1 — отказ старта; `needs_rehash` | -| `app/main.py` | Rate limit **до** KDF, семафор KDF с ограниченной очередью → 429, rehash при входе, `BodyLimit` → 413, health-listener 127.0.0.1:8081 | +| `app/main.py` | Rate limit **до** KDF; допуск ко входу (не больше 2 + 8 на реплику) **до** обращения к БД; семафор KDF с ограниченной очередью → 429; KDF не держит соединение пула, rehash при входе, `BodyLimit` → 413, health-listener 127.0.0.1:8081 | | `migrations/0005_roles.sql` | Гранты ролей api и worker по таблицам и колонкам. Владелец схемы — migrate | | `infra/pki/pki.py` | CA, leaf, ротация, отзыв, CRL; владелец и права файлов под uid каждого образа | | `scripts/lab7.py` | bootstrap / unseal / status / seal / rotate-db-password / rotate-cert / revoke-cert | @@ -180,16 +180,17 @@ docker compose --env-file .env down -v - При успешном входе со старыми параметрами — rehash (лог `auth.rehash`, проверено `security_neg --only argon2`: хэш из lab6 с m=… заменён). - Сессии: в БД — SHA-256 токена. Ошибки входа одинаковые для «нет пользователя» и «неверный пароль»: 401 без подробностей. -**Замер на стенде** (`security_neg --only dos`, реплика API 0,5 CPU): ⟪Docker: N мс⟫ на хэш при m=19 МиБ, t=2, p=1. +**Замер на стенде** (`security_neg --only dos`, реплика API 0,5 CPU): **74,8 мс** на хэш при m=19 МиБ, t=2, p=1. **Обоснование выбора:** оставляем минимум OWASP. -- Он уже даёт ⟪N⟫ мс на попытку. Для атакующего с дампом это ~⟪1000/N⟫ попыток/с на ядро против миллиардов у SHA-256. +- Он уже даёт 74,8 мс на попытку. Для атакующего с дампом это ~13 попыток/с на ядро (и 19 МиБ памяти на каждую параллельную попытку) против миллиардов у SHA-256. - Поднимать m или t на 0,5 CPU — значит делать вход заметно медленнее для пользователей. - Память 19 МиБ × 2 одновременных хэша = 38 МиБ из 256 МиБ лимита реплики. **Бюджет login DoS.** - Одновременно считаются 2 хэша на реплику (`PASSWORD_HASH_CONCURRENCY`), ещё 8 ждут (`PASSWORD_HASH_QUEUE`). Сверх этого — сразу `429 Retry-After: 1`, CPU не тратится. -- Пропускная способность входов ≈ 2 × 2 реплики / ⟪N⟫ мс ≈ ⟪X⟫ входов/с на весь стенд. +- Допуск проверяется **до** запроса в БД: в первом прогоне лишние входы шли к пулу соединений, и при CPU, занятом Argon2id, один из 60 получил 503 (вероятно, таймаут ожидания пула). После переноса проверки вперёд лишние входы получают 429, не трогая БД. +- Пропускная способность входов ≈ 2 × 2 реплики / 74,8 мс ≈ 53 входа/с на весь стенд (верхняя оценка: при лимите 0,5 CPU два параллельных хэша делят одно полуядро). - Перед KDF стоят лимиты Redis: 5 неудач на имя за 5 мин и 120 попыток с IP за минуту. Перебор одного аккаунта упирается в них раньше, чем в CPU. - Всплеск из 60 одновременных входов с неверными паролями: ⟪коды⟫. Остальной API (`GET /users/me`) отвечает с медианой ⟪мс⟫. @@ -238,29 +239,29 @@ docker compose --env-file .env down -v | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл | | --- | --- | --- | --- | -| Публичный smoke по HTTPS | `make test CA_FILE=secrets/ca.crt` | ⟪PASS⟫ | `evidence/smoke.txt` | -| **3:** внешний TLS: недоверенный CA отклоняется | `make test-security` | ⟪…⟫ | `evidence/security.txt` | -| **3:** прежние возможности по HTTPS (lab2–6) | `run.py`, `idempotency.py`, `attachments.py`, `jobs.py` ×5, `observability.py`, `load.py` | ⟪…⟫ | `evidence/student-tests.txt`, `attachments.txt`, `jobs-*.txt`, `observability.txt`, `load.txt` | -| **3:** Argon2id, соль и параметры, ≥ 19 MiB/t=2/p=1, обосновано замером | `security_neg --only argon2 dos` | формат хэша, замер ⟪N мс⟫ | `evidence/security-neg.txt` | -| **3:** LB→API mTLS на каждой реплике: без cert / чужой CA / неверная identity → отказ | `tls_audit --only lb` | ⟪…⟫ | `evidence/tls-audit.txt` | -| **3:** DB, S3, broker, Collector, telemetry, OpenBao — TLS с проверкой сервера; раздельные credentials | `tls_audit` (все разделы) | ⟪…⟫; plaintext везде отклонён | `evidence/tls-audit.txt` | -| **3:** OpenBao не dev, persistent, сервисная auth, scoped policy; нет root в приложении | `tls_audit --only openbao`, `lab7.py status`, persistence | ⟪…⟫ | `evidence/tls-audit.txt`, `stand.txt`, `persistence.txt` | -| **3:** без privileged/host network/docker.sock; non-root; лимиты; наружу только TLS-вход и 127.0.0.1 | `security_neg --only docker`, PORTS | ⟪…⟫ | `evidence/security-neg.txt`, `ports.txt` | -| **3:** секреты не в Git, образе, telemetry | `security_neg --only docker`, `observability.py` | ⟪…⟫ | `evidence/security-neg.txt`, `observability.txt` | -| **3:** rate limit 429 + Retry-After, лимит размера, посторонний, logout/expiry | `security_neg --only acl session ratelimit limits` | ⟪…⟫ | `evidence/security-neg.txt` | -| **3:** перезапуск и отказ реплики через HTTPS с проверкой сертификата | `resilience.py --mode persistence/failover --ca-file …` | ⟪…⟫ | `evidence/persistence.txt`, `failover.txt` | -| **4:** mTLS API/worker→broker и →Collector, разные identities; чужой cert того же CA не даёт прав | `tls_audit --only redis telemetry` | ⟪…⟫ | `evidence/tls-audit.txt` | -| **4:** rehash; измеренный бюджет login DoS; общий для реплик rate limit | `security_neg --only argon2 dos ratelimit` | ⟪…⟫ | `evidence/security-neg.txt` | -| **4:** ротация secret и leaf без пересборки, отзыв старой identity, sealed/expiry | `rotation.py` | ⟪…⟫ | `evidence/rotation.txt` | -| **4:** read_only / no-new-privileges / cap_drop / tmpfs, исключения объяснены | `security_neg --only docker` + раздел Hardening | ⟪…⟫ | `evidence/security-neg.txt` | +| Публичный smoke по HTTPS | `make test CA_FILE=secrets/ca.crt` | PASS | `evidence/smoke.txt` | +| **3:** внешний TLS: недоверенный CA отклоняется | `make test-security` | PASS: свой CA → 200, чужой CA → ошибка проверки | `evidence/security.txt` | +| **3:** прежние возможности по HTTPS (lab2–6) | `run.py`, `idempotency.py`, `attachments.py`, `jobs.py` ×5, `observability.py`, `load.py` | run 30/30, idempotency 16/16, jobs 45/45 (5 сценариев), вложения и наблюдаемость — ⟪после повторного прогона⟫, load 0 ошибок | `evidence/student-tests.txt`, `attachments.txt`, `jobs-*.txt`, `observability.txt`, `load.txt` | +| **3:** Argon2id, соль и параметры, ≥ 19 MiB/t=2/p=1, обосновано замером | `security_neg --only argon2 dos` | `$argon2id$v=19$m=19456,t=2,p=1$…`, соль у каждого своя; 74,8 мс на хэш | `evidence/security-neg.txt` | +| **3:** LB→API mTLS на каждой реплике: без cert / чужой CA / неверная identity → отказ | на обеих репликах: lb → 200; none, rogue (CN=lb), intruder, worker, grafana, plaintext → отказ; неверное имя сервера отвергается клиентом | `evidence/tls-audit.txt` | +| **3:** DB, S3, broker, Collector, telemetry, OpenBao — TLS с проверкой сервера; раздельные credentials | 12 связей, 110 проверок, 0 failed; plaintext везде отклонён | `evidence/tls-audit.txt` | +| **3:** OpenBao не dev, persistent, сервисная auth, scoped policy; нет root в приложении | raft, `sealed: False` после unseal; cert auth: чужая роль/чужой CA → отказ; api: чужой путь, запись, политики, `token/create` → 403; данные пережили рестарт стенда | `evidence/tls-audit.txt`, `stand.txt`, `persistence.txt` | +| **3:** без privileged/host network/docker.sock; non-root; лимиты; наружу только TLS-вход и 127.0.0.1 | опубликованы только 127.0.0.1:8443/8444/8445/3000; 16 внутренних портов закрыты; privileged/host/docker.sock — нет; api/worker — appuser | `evidence/security-neg.txt`, `ports.txt` | +| **3:** секреты не в Git, образе, telemetry | `.env`/`secrets/` в `.gitignore`; в образе нет ключей и секретных ENV; в Loki/Tempo нет пароля, токена, текста, signed URL | `evidence/security-neg.txt`, `observability.txt` | +| **3:** rate limit 429 + Retry-After, лимит размера, посторонний, logout/expiry | посторонний → 404, `X-User-Id` игнорируется; logout → 401, TTL 2 c → 401; 6-я неудача → 429 `Retry-After: 300` на другой реплике; 70 KB → 413 | `evidence/security-neg.txt` | +| **3:** перезапуск и отказ реплики через HTTPS с проверкой сертификата | persistence PASS (вкл. рестарт OpenBao + unseal); failover ×2 PASS, 0 неудачных записей, восстановление 2,1–2,2 c | `evidence/persistence.txt`, `failover.txt` | +| **4:** mTLS API/worker→broker и →Collector, разные identities; чужой cert того же CA не даёт прав | брокер: api = producer, worker = consumer, чужие команды → NOPERM, CN grafana/intruder → NOAUTH; otel-gw: api/worker → 200, grafana/intruder → соединение закрыто | `evidence/tls-audit.txt` | +| **4:** rehash; измеренный бюджет login DoS; общий для реплик rate limit | хэш m=8192,t=1 после входа пересчитан в m=19456,t=2,p=1; бюджет 53 входа/с; счётчик неудач общий для реплик | `evidence/security-neg.txt` | +| **4:** ротация secret и leaf без пересборки, отзыв старой identity, sealed/expiry | 17/17: пароль БД и сертификат lb ротированы без пересборки и без ошибок под нагрузкой; отозванный lb отвергается; sealed 86 c — 0 ошибок | `evidence/rotation.txt` | +| **4:** read_only / no-new-privileges / cap_drop / tmpfs, исключения объяснены | у всех `ro`, `no-new-privileges`, `cap_drop ALL`, лимит памяти; root только у MinIO (без capabilities) | `evidence/security-neg.txt` | | **4:** dependency/image scan с разбором применимости | pip-audit, Trivy | см. «Сканирование» | `evidence/scan-*.txt` | | **4:** ≥ 6 угроз → контроли → отрицательные тесты | `security/THREAT_MODEL.md` | 11 угроз, у каждой тест | — | -| **4:** worker ограничен по CPU/RAM/времени | `app.tools limits-selftest` | ⟪…⟫ | `evidence/worker-limits.txt` | -| **4:** TLS-аудит всей матрицы, ACL, отсутствие утечек в telemetry | `tls_audit`, `observability.py` | ⟪N связей, M проверок, 0 failed⟫ | `evidence/tls-audit.txt` | +| **4:** worker ограничен по CPU/RAM/времени | 5/5: память (RLIMIT_AS 120 МиБ), битый PNG, зависание → kill через 2 c | `evidence/worker-limits.txt` | +| **4:** TLS-аудит всей матрицы, ACL, отсутствие утечек в telemetry | `tls_audit`, `observability.py` | 12 связей, 110 проверок, 0 failed; утечек в telemetry нет | `evidence/tls-audit.txt` | ## Эксперименты и отказы -**Стенд:** Docker Desktop (⟪CPU/RAM хоста⟫), лимиты контейнеров из `compose.yaml`: api 0,5 CPU / 256 МиБ ×2, worker 1 CPU / 1 ГиБ, openbao 0,5 CPU / 256 МиБ. +**Стенд:** Docker Desktop (Windows, Docker Desktop 4.77, Engine 29.5.3), лимиты контейнеров из `compose.yaml`: api 0,5 CPU / 256 МиБ ×2, worker 1 CPU / 1 ГиБ, openbao 0,5 CPU / 256 МиБ. **Фоновая нагрузка `rotation.py`:** - поток записи сообщений; @@ -271,13 +272,13 @@ docker compose --env-file .env down -v | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| `rotate-db-password api` под нагрузкой | 0 ошибок; API подхватил новую версию; прежний пароль не принимается для новых соединений | ⟪…⟫ | ⟪…⟫ | -| `rotate-cert lb` → `revoke-cert lb` | трафик без ошибок; прежний сертификат lb отвергается API | ⟪…⟫ | ⟪…⟫ | -| Отзыв всех токенов cert auth | приложение входит сертификатом заново, запросы без ошибок | ⟪…⟫ | ⟪…⟫ | -| OpenBao sealed, затем рестарт одной реплики API | живая реплика работает на кэше; перезапущенная не готова; LB ведёт на живую; после unseal поднимается | ⟪…⟫ | ⟪…⟫ | -| Перезапуск всего стенда (`scripts/restart.*`, вкл. OpenBao + unseal) | данные и сессия сохранены | ⟪…⟫ | ⟪…⟫ | -| Остановка одной реплики API | запросы идут через вторую | ⟪…⟫ | ⟪…⟫ | -| `tests/load.py` 8 потоков, 60 c через TLS | без ошибок; цена TLS видна в p95 | ⟪RPS, p50/p95/p99⟫ | — | +| `rotate-db-password api` под нагрузкой | 0 ошибок; API подхватил новую версию; прежний пароль не принимается для новых соединений | обе реплики: `secrets version 1 -> 2`; под нагрузкой {201: 318, 200: 319}; новое соединение с прежним паролем → `password authentication failed`; после рестарта API {200: 62, 201: 63} | простоя нет, данные не потеряны | +| `rotate-cert lb` → `revoke-cert lb` | трафик без ошибок; прежний сертификат lb отвергается API | после reload {201: 54, 200: 53}; прежний lb на обеих репликах → `closed by server`; после отзыва {200: 106, 201: 103} | простоя нет | +| Отзыв всех токенов cert auth | приложение входит сертификатом заново, запросы без ошибок | 2 повторных входа, 0 неудачных чтений; {200: 363, 201: 364} | простоя нет | +| OpenBao sealed, затем рестарт одной реплики API | живая реплика работает на кэше; перезапущенная не готова; LB ведёт на живую; после unseal поднимается | 35 c sealed: {200: 285, 201: 287}; 6 событий `secrets.refresh_failed`; перезапущенная реплика unhealthy, трафик {200: 368, 201: 370} через живую | реплика поднялась сама через 12 c после unseal (sealed 86 c); ошибок 0 | +| Перезапуск всего стенда (`scripts/restart.*`, вкл. OpenBao + unseal) | данные и сессия сохранены | PASS: подтверждённые данные и сессия на месте | в пределах 90 c hook-а; потерь нет | +| Остановка одной реплики API | запросы идут через вторую | 2 прогона: 107 и 105 записей, 0 неудачных | первое восстановление 2,1 / 2,2 c; потерь нет | +| `tests/load.py` 8 потоков, 60 c через TLS | без ошибок; цена TLS видна в p95 | 4442 запроса, 0 ошибок, 73,9 RPS; p50 95 мс, p95 287 мс, p99 519 мс | — | ## Сканирование зависимостей и образов @@ -288,7 +289,24 @@ docker compose --env-file .env down -v **Разбор:** для каждой находки — используется ли уязвимый код на нашем пути исполнения и что сделано. -⟪таблица после прогона⟫ +**Итог первого прогона:** +- pip-audit: 66 находок в 2 пакетах; +- Trivy, наш образ: Debian 154 (CRITICAL 9) и Python-пакеты 46 (CRITICAL 5); +- Trivy, инфраструктура: только CRITICAL. + +| Находка | Где | Применимость к нашему пути исполнения | Решение | +| --- | --- | --- | --- | +| Pillow 11.2.1: 59 CVE/GHSA, в т.ч. CRITICAL (переполнения буфера в декодерах/энкодерах, напр. CVE-2026-112393 в `_tiffWriteProc`) | `requirements.txt` → worker декодирует **недоверенные** загрузки | **Применимо.** Worker открывает файлы пользователей: PNG/JPEG пропускаются после собственной проверки заголовков (`app/images.py`), но сам декодер Pillow — на пути атаки. Изоляция (подпроцесс, RLIMIT_AS, таймаут, read-only, без capabilities) снижает ущерб, но не убирает уязвимость | **Обновлено до 13.0.0** (закрывает все находки). Проверено: рендер PNG/JPEG/RGBA, 200 случайно испорченных файлов — только ожидаемые ошибки | +| cryptography 46.0.3: 7 находок (CVE-2026-26007, -69247, -69249 …) | PKI-инструмент, разбор CRL в API | Частично: API разбирает только наш CRL из volume (не от атакующего), PKI запускает оператор. Но библиотека в образе рантайма | **Обновлено до 50.0.2.** Проверено: `pki.py init/issue/revoke`, разбор CRL и `server_context()` | +| Debian 12.8 в `python:3.12.7-slim-bookworm`: openssl CVE-2026-31789 (CRITICAL), gnutls, perl, apt, libcap, krb5 и др. со статусом *fixed* | базовый образ | openssl CVE-2026-31789 — только 32-bit (у нас x86_64); gnutls, krb5, apt, perl приложение не вызывает (Python `ssl` использует OpenSSL, Kerberos не используется). Но пакеты есть в образе | **В Dockerfile добавлен `apt-get upgrade`** в runtime-стадии: все *fixed* обновляются при сборке. Тег базового образа закреплён | +| Debian: *affected* / *will_not_fix* без исправления (zlib CVE-2023-45853 — minizip, sqlite CVE-2025-7458, util-linux, krb5 kadmind) | базовый образ | Не применимо: minizip, sqlite, mount и kadmind приложение не использует; zlib-уязвимость — в minizip, а не в inflate, который использует Pillow | Принято, перепроверять при обновлении базового образа | +| postgres 16.4-alpine, haproxy 3.0.5-alpine, grafana 11.4.0: openssl CVE-2026-31789 (alpine 3.20) | инфраструктура | Только 32-bit платформы — не применимо (amd64) | Принято; при следующем обновлении — свежий patch-релиз образов | +| Go stdlib CVE-2025-68121 (crypto/tls, проверка сертификата при **resumption**) в gosu (postgres) и Grafana | инфраструктура | gosu не делает TLS. Grafana — TLS-клиент к Prometheus/Loki/Tempo в закрытой сети `tstore`; CA не меняется на лету. Наши отрицательные проверки идут новыми соединениями без resumption | Принято с ограничением: обновить Grafana до сборки на Go ≥ 1.24.13 | +| MinIO: amqp091-go CVE-2026-77405/77408/77411 | MinIO | Клиент RabbitMQ нужен только для уведомлений о событиях bucket в AMQP; у нас notify-цели не настроены — код не исполняется | Принято | +| Grafana: kin-openapi GHSA-r277-6w6q-xmqw, grpc-go CVE-2026-33186 | Grafana | Путь — HTTP API Grafana, доступен только оператору на 127.0.0.1:3000 с паролем | Принято; обновление Grafana — следующий шаг | +| redis 8.6.8, openbao 2.6.4, MinIO (ОС) | инфраструктура | CRITICAL нет | — | + +Повторный скан после обновления: ⟪после повторного прогона⟫. ## Ответы на вопросы защиты diff --git a/app/main.py b/app/main.py index 9e8c58a6..a92ce840 100644 --- a/app/main.py +++ b/app/main.py @@ -371,6 +371,25 @@ async def kdf(fn, *args): _kdf_slots.release() +_login_inflight = 0 + + +def login_admit() -> None: + """Допуск ко входу ДО обращения к БД: на реплике одновременно обрабатывается не больше + PASSWORD_HASH_CONCURRENCY + PASSWORD_HASH_QUEUE входов. Остальным сразу 429 — они не + занимают пул соединений БД и не ждут в очереди (иначе всплеск входов при CPU, занятом + Argon2id, упирается в таймаут пула → 503).""" + global _login_inflight + if _login_inflight >= settings.password_hash_concurrency + settings.password_hash_queue: + raise ApiError(429, "rate_limited", "too many password operations, retry later", {"Retry-After": "1"}) + _login_inflight += 1 + + +def login_done() -> None: + global _login_inflight + _login_inflight -= 1 + + def client_ip(request: Request) -> str: """LB перезаписывает X-Forwarded-For адресом клиента; к API ходит только LB (mTLS).""" xff = request.headers.get("x-forwarded-for", "") @@ -498,6 +517,14 @@ async def create_session(request: Request): if wait: logger.warning("login rate limited", extra={"event": "auth.rate_limited", "retry_after": wait}) raise ApiError(429, "rate_limited", "too many login attempts", {"Retry-After": str(wait)}) + login_admit() + try: + return await _login(username, password) + finally: + login_done() + + +async def _login(username: str, password: str) -> dict: async with db.get_pool().connection() as conn: row = await repo.get_credentials(conn, username) stored_hash = row[4] if row else None @@ -509,10 +536,12 @@ async def create_session(request: Request): raise ApiError(401, "unauthorized", "invalid credentials", {"WWW-Authenticate": BASIC_CHALLENGE}) await ratelimit.login_succeeded(username) user = repo.user_out(row) + # Старые параметры/алгоритм → пересчёт с текущими (пароль известен только сейчас). + # Хэш считаем ДО взятия соединения: KDF не держит соединение пула. + new_hash = await kdf(security.hash_password, password) if security.needs_rehash(stored_hash) else None async with db.get_pool().connection() as conn: - if security.needs_rehash(stored_hash): - # Старые параметры/алгоритм → пересчёт с текущими (пароль известен только сейчас). - await repo.update_password_hash(conn, row[0], await kdf(security.hash_password, password)) + if new_hash: + await repo.update_password_hash(conn, row[0], new_hash) logger.info("password hash upgraded", extra={"event": "auth.rehash", "argon2.params": security.params()}) token, expires_at = await sessions.create_session(conn, row[0]) return {"token": token, "token_type": "Bearer", "expires_at": repo.iso(expires_at), "user": user} diff --git a/compose.yaml b/compose.yaml index 68a33d72..0e4a4977 100644 --- a/compose.yaml +++ b/compose.yaml @@ -49,6 +49,10 @@ x-app-env: &app-env SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} SESSION_CACHE_TTL_SECONDS: ${SESSION_CACHE_TTL_SECONDS:-60} IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + # lab7: соединение к PostgreSQL теперь дорогое (TLS + клиентский сертификат + SCRAM), а пул + # растёт по одному соединению. При всплеске входов на 0,5 CPU рост не успевал за 3 c → 503. + # Держим соединения открытыми заранее. + DB_POOL_MIN: ${DB_POOL_MIN:-8} DB_POOL_MAX: ${DB_POOL_MAX:-10} DB_POOL_TIMEOUT: ${DB_POOL_TIMEOUT:-3} DB_STATEMENT_TIMEOUT_MS: ${DB_STATEMENT_TIMEOUT_MS:-5000} diff --git a/evidence/attachments.txt b/evidence/attachments.txt new file mode 100644 index 00000000..bda14341 --- /dev/null +++ b/evidence/attachments.txt @@ -0,0 +1,108 @@ +# attachments +# date: 2026-12-03T16:37:01 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/attachments.py --base-url https://localhost:8443 +== позитивный сценарий == + ok - upload PNG -> 202 (got 202) + ok - 202 queued, variants=[], error_code=null + ok - sha256/size describe the original + ok - no S3 key/bucket in public JSON + ok - upload JPEG with Unicode filename -> 202 (got 202) + ok - filename returned as is (display only) + ok - both become ready (worker) + ok - member downloads PNG -> 200 (got 200) + ok - downloaded bytes are identical (sha256) + ok - true Content-Type image/png + ok - nosniff header + ok - member downloads JPEG (variant=original) -> 200 (got 200) + ok - JPEG bytes and type + ok - message with empty text + 2 attachments -> 201 (got 201) + ok - attachment_ids kept in request order + ok - history shows attachment_ids + ok - text-only POST (lab3) still valid, attachment_ids=[] + ok - member reads metadata -> 200 (got 200) + ok - thumbnail variant exists in lab5 -> 200 (got 200) + ok - unknown variant name -> 400 (got 400) +== доступ == + ok - outsider GET attachment metadata -> 404 (got 404) + ok - unknown attachment metadata -> 404 (got 404) + ok - outsider GET attachment/content -> 404 (got 404) + ok - unknown attachment/content -> 404 (got 404) + ok - anonymous download -> 401 (got 401) + ok - attachment id is not a UUID -> 400 (got 400) + ok - outsider uploads into foreign chat -> 404 (got 404) + ok - anonymous upload -> 401 (got 401) +== привязка к сообщению == + ok - eve uploads into her own chat -> 202 (got 202) + ok - alice uploads into her second chat -> 202 (got 202) + ok - foreign attachment_id (eve's chat) in message -> 404 (got 404) + ok - attachment of ANOTHER chat of the same user -> 404 (got 404) + ok - unknown attachment_id -> 404 (got 404) + ok - one valid + one foreign -> whole message rejected -> 404 (got 404) + ok - duplicate attachment_ids -> 400 (got 400) + ok - same UUID in different case is a duplicate -> 400 (got 400) + ok - more than 10 attachment_ids -> 400 (got 400) + ok - attachment_id is not a UUID -> 400 (got 400) + ok - attachment_ids: null -> 400 (got 400) + ok - blank text without attachments -> 400 (got 400) + ok - text field is required -> 400 (got 400) + ok - any member may reference a chat attachment again -> 201 (got 201) + ok - eve attaches alice's file to her own chat -> 404 (got 404) +== идемпотентность с вложениями == + ok - missing attachment_ids == [] (same Message) + ok - same key, different attachment_ids -> 409 (got 409) + ok - replay with attachments returns the same Message +== размер == + ok - Content-Length = 10 MiB + 1, body never sent (limit before reading) -> 413 (got 413) + ok - Content-Length = 500 MiB -> 413 (got 413) + ok - chunked body > 10 MiB without Content-Length (stream cut at limit) -> 413 (got 413) + ok - real PNG of 11424262 bytes -> 413 (got 413) + ok - empty body -> 400 (got 400) +== пиксели == + ok - decompression bomb 8000x8000 in 62290 bytes -> 413 (got 413) + ok - 40 040 001 pixels (just over the limit) -> 413 (got 413) +== повреждённые файлы == + ok - truncated PNG -> 415 (got 415) + ok - truncated PNG: error code + ok - PNG with flipped byte (CRC) -> 415 (got 415) + ok - PNG with flipped byte (CRC): error code + ok - PNG signature only -> 415 (got 415) + ok - PNG signature only: error code + ok - PNG header + garbage -> 415 (got 415) + ok - PNG header + garbage: error code + ok - truncated JPEG -> 415 (got 415) + ok - truncated JPEG: error code + ok - JPEG SOI + garbage -> 415 (got 415) + ok - JPEG SOI + garbage: error code +== fuzz: случайные порчи байтов (только 202 или 415, никогда 500) == + ok - 30 corrupted files -> only 202/415 (got [202, 415]) +== подмена MIME == + ok - PNG bytes sent as image/jpeg -> 415 (got 415) + ok - JPEG bytes sent as image/png -> 415 (got 415) + ok - text renamed to .png -> 415 (got 415) + ok - GIF sent as image/png -> 415 (got 415) + ok - HTML sent as image/jpeg -> 415 (got 415) + ok - PNG with Content-Type image/gif -> 415 (got 415) + ok - PNG with Content-Type application/octet-stream -> 415 (got 415) + ok - PNG with Content-Type text/html -> 415 (got 415) +== опасные filename == + ok - filename '../../etc/passwd' -> 400 (got 400) + ok - filename 'dir/a.png' -> 400 (got 400) + ok - filename 'C:\\Windows\\a.png' -> 400 (got 400) + ok - filename 'a\x00.png' -> 400 (got 400) + ok - filename 'a\nb.png' -> 400 (got 400) + ok - filename 'tab\t.png' -> 400 (got 400) + ok - filename '\x1b[31mred.png' -> 400 (got 400) + ok - filename 'photo\u202egnp.exe' -> 400 (got 400) + ok - filename '..' -> 400 (got 400) + ok - filename '.' -> 400 (got 400) + ok - filename ' ' -> 400 (got 400) + ok - filename 'xxxxxxxxxxxxxxxxxxxx' -> 400 (got 400) + ok - filename missing -> 400 (got 400) + ok - filename of exactly 255 chars -> 202 (got 202) + ok - filename with spaces, Unicode and punctuation -> 202 (got 202) + ok - media type parameters are ignored -> 202 (got 202) + ok - no 500 and no dropped connection among 99 checked responses + +91 passed, 0 failed +[exit 0] diff --git a/evidence/check.txt b/evidence/check.txt new file mode 100644 index 00000000..43752206 --- /dev/null +++ b/evidence/check.txt @@ -0,0 +1,6 @@ +# check +# date: 2026-12-03T00:23:10 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +[exit 0] diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 00000000..dba12f8c --- /dev/null +++ b/evidence/failover.txt @@ -0,0 +1,56 @@ +# failover +# date: 2026-12-03T16:51:52 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe tests/resilience.py --mode failover --action-script C:\Users\79152\Desktop\mtusi2026lab7\scripts\stop-one.cmd --base-url https://localhost:8443 --ca-file C:\Users\79152\Desktop\mtusi2026lab7\secrets\ca.crt +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 108, "failed_attempts": 0, "first_recovery_seconds": 2.199} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. +[exit 0] + +$ C:\Users\79152\Desktop\mtusi2026lab7\scripts\restore-api.cmd + Container mtusi-lab7-openbao-1 Waiting + Container mtusi-lab7-postgres-1 Waiting + Container mtusi-lab7-postgres-1 Healthy + Container mtusi-lab7-openbao-1 Healthy + Container mtusi-lab7-migrate-1 Starting + Container mtusi-lab7-migrate-1 Started + Container mtusi-lab7-broker-1 Waiting + Container mtusi-lab7-openbao-1 Waiting + Container mtusi-lab7-migrate-1 Waiting + Container mtusi-lab7-postgres-1 Waiting + Container mtusi-lab7-redis-1 Waiting + Container mtusi-lab7-broker-1 Healthy + Container mtusi-lab7-postgres-1 Healthy + Container mtusi-lab7-redis-1 Healthy + Container mtusi-lab7-openbao-1 Healthy + Container mtusi-lab7-migrate-1 Exited + Container mtusi-lab7-api-2 Starting + Container mtusi-lab7-api-2 Started +[exit 0] + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe tests/resilience.py --mode failover --action-script C:\Users\79152\Desktop\mtusi2026lab7\scripts\stop-one.cmd --base-url https://localhost:8443 --ca-file C:\Users\79152\Desktop\mtusi2026lab7\secrets\ca.crt +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 111, "failed_attempts": 0, "first_recovery_seconds": 2.228} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. +[exit 0] + +$ C:\Users\79152\Desktop\mtusi2026lab7\scripts\restore-api.cmd + Container mtusi-lab7-openbao-1 Waiting + Container mtusi-lab7-postgres-1 Waiting + Container mtusi-lab7-openbao-1 Healthy + Container mtusi-lab7-postgres-1 Healthy + Container mtusi-lab7-migrate-1 Starting + Container mtusi-lab7-migrate-1 Started + Container mtusi-lab7-postgres-1 Waiting + Container mtusi-lab7-redis-1 Waiting + Container mtusi-lab7-broker-1 Waiting + Container mtusi-lab7-openbao-1 Waiting + Container mtusi-lab7-migrate-1 Waiting + Container mtusi-lab7-postgres-1 Healthy + Container mtusi-lab7-redis-1 Healthy + Container mtusi-lab7-openbao-1 Healthy + Container mtusi-lab7-broker-1 Healthy + Container mtusi-lab7-migrate-1 Exited + Container mtusi-lab7-api-2 Starting + Container mtusi-lab7-api-2 Started +[exit 0] diff --git a/evidence/jobs-broker-down.txt b/evidence/jobs-broker-down.txt new file mode 100644 index 00000000..49e8aded --- /dev/null +++ b/evidence/jobs-broker-down.txt @@ -0,0 +1,17 @@ +# jobs-broker-down +# date: 2026-12-03T00:25:59 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/jobs.py --base-url https://localhost:8443 --scenario broker-down +== брокер недоступен: приём не зависит от брокера (transactional outbox) == + ok - /health/ready = 200: broker is not critical for API + ok - upload → 202 queued while broker is down (0.1s, publish timeout ≤ 2s) + ok - intent kept in outbox, not published yet + ok - after broker is back: status ready, error_code null + ok - after broker is back: variants thumbnail+crop+optimized (['thumbnail', 'crop', 'optimized']) + ok - after broker is back: original byte-for-byte + ok - after broker is back: thumbnail 256x160, sha256 matches + ok - relay published the outbox row when broker came back + [broker-down: 10s] + +8 passed, 0 failed +[exit 0] diff --git a/evidence/jobs-crash-ack.txt b/evidence/jobs-crash-ack.txt new file mode 100644 index 00000000..f4573f10 --- /dev/null +++ b/evidence/jobs-crash-ack.txt @@ -0,0 +1,15 @@ +# jobs-crash-ack +# date: 2026-12-03T00:26:34 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/jobs.py --base-url https://localhost:8443 --scenario crash-ack +== crash после COMMIT ready, до ack == + ok - commit before crash: status ready, error_code null + ok - commit before crash: variants thumbnail+crop+optimized (['thumbnail', 'crop', 'optimized']) + ok - commit before crash: original byte-for-byte + ok - commit before crash: thumbnail 256x160, sha256 matches + ok - unacked message redelivered after restart and acked as no-op + ok - ready recorded once, 3 variants + [crash-ack: 28s] + +6 passed, 0 failed +[exit 0] diff --git a/evidence/jobs-redelivery.txt b/evidence/jobs-redelivery.txt new file mode 100644 index 00000000..24fa6726 --- /dev/null +++ b/evidence/jobs-redelivery.txt @@ -0,0 +1,15 @@ +# jobs-redelivery +# date: 2026-12-03T00:26:09 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/jobs.py --base-url https://localhost:8443 --scenario redelivery +== повторная доставка уже ready-задачи == + published duplicate: 1796253978409-0 {"schema_version": 1, "job_id": "22d1f07d-a118-4d98-8e87-ad8acb323053", "type": "at + published duplicate: 1796253982127-0 {"schema_version": 1, "job_id": "22d1f07d-a118-4d98-8e87-ad8acb323053", "type": "at + ok - duplicates: status stays ready, variants unchanged (same sha256) + ok - no second set of variants: rows=3, S3 objects=3 + ok - job finished exactly once, attempt unchanged + ok - duplicates acked (no pending messages) + [redelivery: 24s] + +4 passed, 0 failed +[exit 0] diff --git a/evidence/jobs-registry.txt b/evidence/jobs-registry.txt new file mode 100644 index 00000000..15629f3b --- /dev/null +++ b/evidence/jobs-registry.txt @@ -0,0 +1,19 @@ +# jobs-registry +# date: 2026-12-03T00:29:14 commit: cbbe525 + +$ docker compose --env-file .env exec -T worker python -m app.replay --list +failed jobs: 0 +[exit 0] + +$ docker compose --env-file .env exec -T worker python -m app.replay --dlq +1796254126700-0 {"job": "{\"attachment_id\":\"c77ba66f-95d6-477f-8b99-845b2ba9578d\",\"job_id\":\"7cb09627-2683-46ed-8e28-506b56cd339d\"}", "reason": "retry_exhausted (injected_transient)", "source_id": "1796254126662-0", "at": "2026-12-02T23:28:46.700642Z"} +[exit 0] + +$ docker compose --env-file .env exec -T worker python -m app.tools queue +{"stream_length": 0, "groups": [{"name": "workers", "consumers": 4, "pending": 0, "lag": 0}], "dlq_length": 1, "outbox_unpublished": 0, "jobs_by_status": {"ready": 25}} +[exit 0] + +$ docker compose --env-file .env --profile fault stop api-fault worker-fault + Container mtusi-lab7-worker-fault-1 Stopping + Container mtusi-lab7-worker-fault-1 Stopped +[exit 0] diff --git a/evidence/jobs-retry-replay.txt b/evidence/jobs-retry-replay.txt new file mode 100644 index 00000000..79ec16b2 --- /dev/null +++ b/evidence/jobs-retry-replay.txt @@ -0,0 +1,22 @@ +# jobs-retry-replay +# date: 2026-12-03T00:27:02 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/jobs.py --base-url https://localhost:8443 --scenario retry-replay +== временные ошибки → backoff+jitter → failed → replay == + ok - after 23s: failed, error_code=retry_exhausted + ok - bounded: 5 attempts, 4 scheduled retries, delays [0.8, 1.2, 3.8, 6.3] + ok - backoff grows 2^n with jitter in [d/2, d] (JOB_BACKOFF_BASE_SECONDS=1) + ok - content of failed → 409 (got 409) + ok - failed attachment cannot be attached → 409 (got 409) + ok - failed job is in the registry (python -m app.replay --list) + ok - explicit replay accepted + ok - after replay: status ready, error_code null + ok - after replay: variants thumbnail+crop+optimized (['thumbnail', 'crop', 'optimized']) + ok - after replay: original byte-for-byte + ok - after replay: thumbnail 256x160, sha256 matches + ok - same job_id, attempt 6, replays=1 (audit) + ok - replay of a ready job is refused (no duplicate execution) + [retry-replay: 131s] + +13 passed, 0 failed +[exit 0] diff --git a/evidence/jobs-worker-down.txt b/evidence/jobs-worker-down.txt new file mode 100644 index 00000000..0ab40b8a --- /dev/null +++ b/evidence/jobs-worker-down.txt @@ -0,0 +1,26 @@ +# jobs-worker-down +# date: 2026-12-03T00:25:23 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/jobs.py --base-url https://localhost:8443 --scenario worker-down +== worker остановлен: приём не зависит от обработки == + ok - upload → 202 queued without worker (0.06s) + ok - still queued after 3 s: API did not resize synchronously + ok - content of queued attachment → 409 (got 409) + ok - thumbnail of queued attachment → 409 (got 409) + ok - message with queued attachment → 201 (got 201) + ok - other messages keep working + ok - job is in the broker stream (len=1), outbox published +== рестарт брокера и API с сохранением volumes == + ok - after broker restart the message is still there (len=1) + ok - same session, same attachment, still queued +== worker запущен == + ok - after restart: status ready, error_code null + ok - after restart: variants thumbnail+crop+optimized (['thumbnail', 'crop', 'optimized']) + ok - after restart: original byte-for-byte + ok - after restart: thumbnail 256x160, sha256 matches + ok - staging removed after ready (original lives in originals/) + attachment 6aa5c5be-15a2-415a-94b1-fad82336be4d, job 8acaba04-3508-4e29-a7c1-3588390ff9ee, events: ['23:25:26.464 accepted 1 api', '23:25:51.164 claimed 1 41fdf4c607ce-1', '23:25:52.695 ready 1 41fdf4c607ce'] + [worker-down: 35s] + +14 passed, 0 failed +[exit 0] diff --git a/evidence/load.json b/evidence/load.json new file mode 100644 index 00000000..eea9751c --- /dev/null +++ b/evidence/load.json @@ -0,0 +1,17 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.124, + "concurrency": 8, + "successful_requests": 4442, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 73.881, + "successful_latency_ms": { + "p50": 95.356, + "p95": 287.379, + "p99": 519.151 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/load.txt b/evidence/load.txt new file mode 100644 index 00000000..85759aed --- /dev/null +++ b/evidence/load.txt @@ -0,0 +1,63 @@ +# load +# date: 2026-12-03T00:29:40 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe tests/load.py --base-url https://localhost:8443 --ca-file C:\Users\79152\Desktop\mtusi2026lab7\secrets\ca.crt --duration 60 --concurrency 8 --output evidence/load.json +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.124, + "concurrency": 8, + "successful_requests": 4442, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 73.881, + "successful_latency_ms": { + "p50": 95.356, + "p95": 287.379, + "p99": 519.151 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} +[exit 0] + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/snapshot.py --minutes 2 +Окно: последние 2 мин + + API RPS (все реплики) 39.64 req/s sum(rate(http_server_request_duration_seconds_count[2m])) + API доля 5xx 0.00 % (sum(rate(http_server_request_duration_seconds_count{http_response_status_code=~"5.."}[2m])) or vector(0)) / sum(rate(http_server_request_duration_seconds_count[2m])) + API p50 70 ms histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket[2m]))) + API p95 244 ms histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket[2m]))) + API p99 481 ms histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket[2m]))) + Доступность за 1h (SLO ≥ 99 %) 100.00 % 1 - messenger:http_errors:ratio1h + Jobs ready 0 sum(increase(messenger_jobs_processed_total{outcome="ready"}[2m])) + Jobs retry 0 sum(increase(messenger_jobs_processed_total{outcome="retry"}[2m])) + Jobs failed 0 sum(increase(messenger_jobs_processed_total{outcome="failed"}[2m])) + Job duration p95 (ready) нет данных histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome="ready"}[2m]))) + Upload → ready p50 нет данных histogram_quantile(0.50, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[2m]))) + Upload → ready p95 нет данных histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[2m]))) + Очередь: queued сейчас 0 max(messenger_queue_depth{state="queued"}) + Очередь: oldest age max за окно 33.09 s max_over_time(messenger:queue_oldest_age_seconds:max[2m]) + DB pool used max за окно 6 max(max_over_time(messenger_db_pool_connections{state="used"}[2m])) + DB pool waiting max за окно 0 max(max_over_time(messenger_db_pool_waiting[2m])) + Worker утилизация max за окно 0.00 % max_over_time((sum(messenger_worker_busy) / sum(messenger_worker_capacity))[2m:15s]) + CPU API (ядра, сумма реплик) 0.47 sum(rate(process_cpu_time_seconds_total{job="messenger-api"}[2m])) + CPU worker (ядра) 0.00 sum(rate(process_cpu_time_seconds_total{job="messenger-worker"}[2m])) + RSS API max 166 MiB max(process_memory_usage_bytes{job="messenger-api"}) + RSS worker max 105 MiB max(process_memory_usage_bytes{job="messenger-worker"}) + RSS Collector 219 MiB max(otelcol_process_memory_rss{job="otel-collector"}) + Collector: spans отправлено 25462 sum(increase(otelcol_exporter_sent_spans_total[2m])) + Collector: логов отправлено 5094 sum(increase(otelcol_exporter_sent_log_records_total[2m])) + Collector: потеряно (send_failed) 0 sum(increase({__name__=~"otelcol_exporter_send_failed_.+"}[2m])) + Серий метрик приложения 460 count({__name__=~"messenger_.+|http_server_.+"}) + +Alerts: + ApiHighErrorRate inactive health=ok for=60s + ApiErrorBudgetBurnFast inactive health=ok for=120s + ApiLatencyP95High inactive health=ok for=300s + AttachmentQueueLagGrowing inactive health=ok for=30s + AttachmentJobsFailing inactive health=ok for=0s + TimeToReadySloBreach inactive health=ok for=300s + TelemetryExportFailing inactive health=ok for=60s + OtelCollectorDown inactive health=ok for=60s +[exit 0] diff --git a/evidence/metrics-snapshot.txt b/evidence/metrics-snapshot.txt new file mode 100644 index 00000000..28b42a44 --- /dev/null +++ b/evidence/metrics-snapshot.txt @@ -0,0 +1,43 @@ +# metrics-snapshot +# date: 2026-12-03T00:35:15 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/snapshot.py --minutes 30 +Окно: последние 30 мин + + API RPS (все реплики) 4.71 req/s sum(rate(http_server_request_duration_seconds_count[30m])) + API доля 5xx 0.00 % (sum(rate(http_server_request_duration_seconds_count{http_response_status_code=~"5.."}[30m])) or vector(0)) / sum(rate(http_server_request_duration_seconds_count[30m])) + API p50 21 ms histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket[30m]))) + API p95 230 ms histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket[30m]))) + API p99 615 ms histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket[30m]))) + Доступность за 1h (SLO ≥ 99 %) 100.00 % 1 - messenger:http_errors:ratio1h + Jobs ready 23.46 sum(increase(messenger_jobs_processed_total{outcome="ready"}[30m])) + Jobs retry 1.20 sum(increase(messenger_jobs_processed_total{outcome="retry"}[30m])) + Jobs failed 0 sum(increase(messenger_jobs_processed_total{outcome="failed"}[30m])) + Job duration p95 (ready) 4.71 s histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome="ready"}[30m]))) + Upload → ready p50 7.08 s histogram_quantile(0.50, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[30m]))) + Upload → ready p95 26.17 s histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[30m]))) + Очередь: queued сейчас 0 max(messenger_queue_depth{state="queued"}) + Очередь: oldest age max за окно 33.09 s max_over_time(messenger:queue_oldest_age_seconds:max[30m]) + DB pool used max за окно 8 max(max_over_time(messenger_db_pool_connections{state="used"}[30m])) + DB pool waiting max за окно 0 max(max_over_time(messenger_db_pool_waiting[30m])) + Worker утилизация max за окно 100.00 % max_over_time((sum(messenger_worker_busy) / sum(messenger_worker_capacity))[30m:15s]) + CPU API (ядра, сумма реплик) 0.07 sum(rate(process_cpu_time_seconds_total{job="messenger-api"}[30m])) + CPU worker (ядра) 0.01 sum(rate(process_cpu_time_seconds_total{job="messenger-worker"}[30m])) + RSS API max 148 MiB max(process_memory_usage_bytes{job="messenger-api"}) + RSS worker max 106 MiB max(process_memory_usage_bytes{job="messenger-worker"}) + RSS Collector 220 MiB max(otelcol_process_memory_rss{job="otel-collector"}) + Collector: spans отправлено 41403 sum(increase(otelcol_exporter_sent_spans_total[30m])) + Collector: логов отправлено 9003 sum(increase(otelcol_exporter_sent_log_records_total[30m])) + Collector: потеряно (send_failed) 0 sum(increase({__name__=~"otelcol_exporter_send_failed_.+"}[30m])) + Серий метрик приложения 415 count({__name__=~"messenger_.+|http_server_.+"}) + +Alerts: + ApiHighErrorRate inactive health=ok for=60s + ApiErrorBudgetBurnFast inactive health=ok for=120s + ApiLatencyP95High inactive health=ok for=300s + AttachmentQueueLagGrowing inactive health=ok for=30s + AttachmentJobsFailing inactive health=ok for=0s + TimeToReadySloBreach inactive health=ok for=300s + TelemetryExportFailing inactive health=ok for=60s + OtelCollectorDown inactive health=ok for=60s +[exit 0] diff --git a/evidence/no-local-file.txt b/evidence/no-local-file.txt new file mode 100644 index 00000000..a909cf5e --- /dev/null +++ b/evidence/no-local-file.txt @@ -0,0 +1,14 @@ +# no-local-file +# date: 2026-12-03T00:30:58 commit: cbbe525 + +$ docker compose --env-file .env exec -T --index 1 api python -m app.tools find-local 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75 +{"files_scanned": 68, "copies_found": []} +[exit 0] + +$ docker compose --env-file .env exec -T --index 2 api python -m app.tools find-local 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75 +{"files_scanned": 68, "copies_found": []} +[exit 0] + +$ docker compose --env-file .env exec -T worker python -m app.tools find-local 99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75 +{"files_scanned": 69, "copies_found": []} +[exit 0] diff --git a/evidence/observability.txt b/evidence/observability.txt new file mode 100644 index 00000000..60215844 --- /dev/null +++ b/evidence/observability.txt @@ -0,0 +1,66 @@ +# observability +# date: 2026-12-03T15:52:36 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/observability.py --base-url https://localhost:8443 +== контролируемый запрос: trace и лог API == + ok - POST message с traceparent → 201 (trace_id 1ae3d87a08721a93694e2434225a0e5f) + ok - Tempo: server span messenger-api найден (5 spans) + ok - server span: http.route = шаблон (/api/v1/chats/{chat_id}/messages) + ok - server span: status_code 201 + ok - server span: messenger.request.id = X-Request-Id (320416f3-e160-4f7a-a69b-d9ea52bd580b) + ok - resource: service.version=lab6 instance=6460ef39fa5f env=lab + ok - trace запроса содержит DB spans (psycopg) + ok - Loki: лог API с тем же trace_id (1 записей) + ok - лог: request.id = X-Request-Id ответа + ok - лог: span_id=6a7f43a09866f9db, severity=INFO, service_name=messenger-api +== upload: producer → consumer → S3/DB в одном trace == + ok - upload с traceparent → 202 (trace_id cbdacab0546872a165574b7ef21402f8) + ok - attachment → ready + ok - producer span «send attachments:jobs» в API + ok - consumer span «process attachments:jobs» в worker + ok - consumer.parent = producer span (W3C traceparent через сообщение broker) + ok - consumer: outcome=ready + ok - worker → S3 spans: ['S3.CopyObject', 'S3.DeleteObject', 'S3.GetObject', 'S3.PutObject'] + ok - worker → DB spans: 19 + ok - worker: span image.render + цепочка: api:POST /api/v1/chats/{chat_id}/attachments → api:send attachments:jobs → worker:process attachments:jobs → worker:image.render + ok - Loki: лог worker job.ready с тем же trace_id (2 записей) +== retry: все попытки задачи в одном trace == + SKIP: trace с retry не найден — сначала jobs.py --scenario retry-replay (профиль fault) +== метрики контракта в Prometheus == + ok - http_server_request_duration_seconds_bucket: 1590 серий, job=['messenger-api'] + ok - messenger_jobs_processed_total: 2 серий, job=['messenger-worker'] + ok - messenger_job_duration_seconds_bucket: 28 серий, job=['messenger-worker'] + ok - messenger_attachment_time_to_ready_seconds_bucket: 30 серий, job=['messenger-worker'] + ok - messenger_queue_depth: 15 серий, job=['messenger-api'] + ok - messenger_queue_oldest_age_seconds: 5 серий, job=['messenger-api'] + ok - messenger_db_pool_connections: 14 серий, job=['messenger-api', 'messenger-worker'] + ok - messenger_db_pool_waiting: 7 серий, job=['messenger-api', 'messenger-worker'] + ok - messenger_db_pool_max: 7 серий, job=['messenger-api', 'messenger-worker'] + ok - messenger_worker_busy: 2 серий, job=['messenger-worker'] + ok - messenger_worker_capacity: 2 серий, job=['messenger-worker'] + ok - process_cpu_time_seconds_total: 14 серий, job=['messenger-api', 'messenger-worker'] + ok - process_memory_usage_bytes: 7 серий, job=['messenger-api', 'messenger-worker'] + ok - http_route — только шаблоны (10 значений, UUID нет) + ok - p95 считается из buckets (histogram_quantile по sum by le) + ok - buckets HTTP в секундах: 0.005 … 10.0 + ok - target_info (resource) для ['messenger-api', 'messenger-worker'] +== кардинальность и утечки == + ok - нет запрещённых labels у метрик приложения (ok) + ok - кардинальность ограничена: ≤ 507 серий на процесс, 35 комбинаций route×method×code + ok - Loki: пароль не найден в логах + ok - Loki: Bearer token не найден в логах + ok - Loki: текст сообщения не найден в логах + ok - Tempo: в атрибутах spans нет пароля/токена/текста/signed URL [] + ok - db.statement — с плейсхолдерами %s, без значений (4 запросов) +== provisioning == + ok - alert rule ApiHighErrorRate загружен (inactive, for=60s) + ok - alert rule AttachmentQueueLagGrowing загружен (inactive, for=30s) + ok - Grafana datasource prom: Successfully queried the Prometheus API. + ok - Grafana datasource loki: Data source successfully connected. + ok - Grafana datasource tempo: health API не реализован плагином; поиск через datasource (mTLS) → 200, трасс: 1 + ok - dashboard «Messenger — lab6» из provisioning: 21 панелей, provisioned=True + [observability: 29s] + +50 passed, 0 failed +[exit 0] diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..77a39dd3 --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,45 @@ +# persistence +# date: 2026-12-03T16:51:35 commit: cbbe525 + +$ docker compose --env-file .env ps +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab7-api-1 mtusi-messenger:lab7 "python -m app" api 52 minutes ago Up 52 minutes (healthy) 8443/tcp +mtusi-lab7-api-2 mtusi-messenger:lab7 "python -m app" api 52 minutes ago Up 52 minutes (healthy) 8443/tcp +mtusi-lab7-broker-1 redis:8.6.8 "docker-entrypoint.s…" broker 17 hours ago Up 16 hours (healthy) 6379/tcp +mtusi-lab7-grafana-1 grafana/grafana:11.4.0 "/bin/sh -c 'export …" grafana 17 hours ago Up 17 hours 127.0.0.1:3000->3000/tcp +mtusi-lab7-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb 17 hours ago Up 55 seconds (healthy) 127.0.0.1:8443-8445->8443-8445/tcp +mtusi-lab7-loki-1 grafana/loki:3.3.2 "/usr/bin/loki -conf…" loki 17 hours ago Up 17 hours 3100/tcp +mtusi-lab7-openbao-1 openbao/openbao:2.6.4 "bao server -config=…" openbao 17 hours ago Up 16 hours (healthy) 8200/tcp +mtusi-lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.111.0 "/otelcol-contrib --…" otel-collector 17 hours ago Up 17 hours +mtusi-lab7-otel-gw-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" otel-gw 17 hours ago Up 17 hours (healthy) +mtusi-lab7-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 17 hours ago Up 16 hours (healthy) 5432/tcp +mtusi-lab7-prometheus-1 prom/prometheus:v2.55.1 "/bin/prometheus --c…" prometheus 17 hours ago Up 17 hours (healthy) 9090/tcp +mtusi-lab7-redis-1 redis:8.6.8 "docker-entrypoint.s…" redis 17 hours ago Up 16 hours (healthy) 6379/tcp +mtusi-lab7-s3-1 pgsty/minio:RELEASE.2026-08-04T00-00-00Z "/usr/bin/docker-ent…" s3 17 hours ago Up 16 hours (healthy) 9000/tcp +mtusi-lab7-tempo-1 grafana/tempo:2.6.1 "/tempo -config.file…" tempo 17 hours ago Up 16 hours +mtusi-lab7-worker-1 mtusi-messenger:lab7 "python -m app.worker" worker 52 minutes ago Up 52 minutes (healthy) 8443/tcp +[exit 0] + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe tests/resilience.py --mode persistence --action-script C:\Users\79152\Desktop\mtusi2026lab7\scripts\restart.cmd --base-url https://localhost:8443 --ca-file C:\Users\79152\Desktop\mtusi2026lab7\secrets\ca.crt +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +[exit 0] + +$ docker compose --env-file .env ps +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab7-api-1 mtusi-messenger:lab7 "python -m app" api 53 minutes ago Up 5 seconds (health: starting) 8443/tcp +mtusi-lab7-api-2 mtusi-messenger:lab7 "python -m app" api 53 minutes ago Up 5 seconds (health: starting) 8443/tcp +mtusi-lab7-broker-1 redis:8.6.8 "docker-entrypoint.s…" broker 17 hours ago Up 7 seconds (health: starting) 6379/tcp +mtusi-lab7-grafana-1 grafana/grafana:11.4.0 "/bin/sh -c 'export …" grafana 17 hours ago Up 17 hours 127.0.0.1:3000->3000/tcp +mtusi-lab7-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb 17 hours ago Up 6 seconds (health: starting) 127.0.0.1:8443-8445->8443-8445/tcp +mtusi-lab7-loki-1 grafana/loki:3.3.2 "/usr/bin/loki -conf…" loki 17 hours ago Up 17 hours 3100/tcp +mtusi-lab7-openbao-1 openbao/openbao:2.6.4 "bao server -config=…" openbao 17 hours ago Up 12 seconds (healthy) 8200/tcp +mtusi-lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.111.0 "/otelcol-contrib --…" otel-collector 17 hours ago Up 17 hours +mtusi-lab7-otel-gw-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" otel-gw 17 hours ago Up 17 hours (healthy) +mtusi-lab7-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 17 hours ago Up 7 seconds (health: starting) 5432/tcp +mtusi-lab7-prometheus-1 prom/prometheus:v2.55.1 "/bin/prometheus --c…" prometheus 17 hours ago Up 17 hours (healthy) 9090/tcp +mtusi-lab7-redis-1 redis:8.6.8 "docker-entrypoint.s…" redis 17 hours ago Up 8 seconds (healthy) 6379/tcp +mtusi-lab7-s3-1 pgsty/minio:RELEASE.2026-08-04T00-00-00Z "/usr/bin/docker-ent…" s3 17 hours ago Up 8 seconds (healthy) 9000/tcp +mtusi-lab7-tempo-1 grafana/tempo:2.6.1 "/tempo -config.file…" tempo 17 hours ago Up 16 hours +mtusi-lab7-worker-1 mtusi-messenger:lab7 "python -m app.worker" worker 53 minutes ago Up 6 seconds (health: starting) 8443/tcp +[exit 0] diff --git a/evidence/ports.txt b/evidence/ports.txt new file mode 100644 index 00000000..02740f2f --- /dev/null +++ b/evidence/ports.txt @@ -0,0 +1,18 @@ +# ports +# date: 2026-12-03T00:24:32 commit: cbbe525 +127.0.0.1:5432 closed (TimeoutError) ok +127.0.0.1:6379 closed (TimeoutError) ok +127.0.0.1:9000 closed (TimeoutError) ok +127.0.0.1:9001 closed (TimeoutError) ok +127.0.0.1:8200 closed (TimeoutError) ok +127.0.0.1:8201 closed (TimeoutError) ok +127.0.0.1:4317 closed (TimeoutError) ok +127.0.0.1:4318 closed (TimeoutError) ok +127.0.0.1:8888 closed (TimeoutError) ok +127.0.0.1:13133 closed (TimeoutError) ok +127.0.0.1:9090 closed (TimeoutError) ok +127.0.0.1:3100 closed (TimeoutError) ok +127.0.0.1:3200 closed (TimeoutError) ok +127.0.0.1:8081 closed (TimeoutError) ok +127.0.0.1:8404 closed (TimeoutError) ok +127.0.0.1:8080 closed (TimeoutError) ok diff --git a/evidence/queue-drain.txt b/evidence/queue-drain.txt new file mode 100644 index 00000000..925aef3d --- /dev/null +++ b/evidence/queue-drain.txt @@ -0,0 +1,7 @@ +# queue-drain +# date: 2026-12-03T00:31:05 commit: cbbe525 +queue drained in 1.6 s: {'ready': 26} + +$ docker compose --env-file .env exec -T worker python -m app.tools queue +{"stream_length": 0, "groups": [{"name": "workers", "consumers": 4, "pending": 0, "lag": 0}], "dlq_length": 1, "outbox_unpublished": 0, "jobs_by_status": {"ready": 26}} +[exit 0] diff --git a/evidence/rotation.txt b/evidence/rotation.txt new file mode 100644 index 00000000..fa7c4524 --- /dev/null +++ b/evidence/rotation.txt @@ -0,0 +1,87 @@ +# rotation +# date: 2026-12-03T00:31:08 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/rotation.py --base-url https://localhost:8443 +== Ротация пароля БД роли api под нагрузкой + kv/messenger/api: version 2 (current + previous password) + ALTER ROLE api: old password no longer accepted for NEW connections + api picks up version 2 within SECRETS_REFRESH_SECONDS; open connections keep working + ok - API подхватил новую версию секретов: ['secrets version 1 -> 2', 'secrets version 1 -> 2'] + ok - под нагрузкой во время ротации: {201: 318, 200: 319} + ok rotation в KV есть текущий и предыдущий пароль -> yes + ok rotation новое соединение с ТЕКУЩИМ паролем -> OK:api + ok rotation новое соединение с ПРЕДЫДУЩИМ паролем -> password authentication failed for user "api" + ok - прежний пароль отклоняется для новых соединений, текущий принимается + ok - после рестарта API (только новый пароль, образ тот же): {200: 62, 201: 63} + [db-password: 71s] +== Ротация leaf-сертификата lb и отзыв прежнего + issued lb: serial 28e9b2f37c486e379fc949b3395d06be16ce8083, expires 2027-03-02 + ok - трафик через LB после reload с новым сертификатом: {201: 54, 200: 53} + revoked lb serial 5e4750312ca6226a75e26ae95c920569649c1ccf; CRL now has 1 entries + ok lb→api 172.25.0.2 identity lb (разрешена) -> 200 + ok lb→api 172.25.0.2 отозванный lb 5e4750312c… -> closed by server + ok lb→api 172.25.0.3 identity lb (разрешена) -> 200 + ok lb→api 172.25.0.3 отозванный lb 5e4750312c… -> closed by server + ok - API отвергает новое соединение с ОТОЗВАННЫМ прежним сертификатом lb + ok - вся матрица LB → API после ротации: разрешён только действующий lb + ok - трафик через LB после отзыва прежнего сертификата: {200: 106, 201: 103} + [cert: 24s] +== Отзыв токенов OpenBao приложения + ok - оператор отозвал все токены, выданные cert auth + ok - API вошёл заново сертификатом (2 входов), неудачных чтений: 0 + ok - запросы во время отзыва: {200: 363, 201: 364} + [token: 48s] +== OpenBao sealed: работающие реплики живут на кэше, новые не стартуют + ok - 35 c при sealed OpenBao: {200: 285, 201: 287} (секреты из кэша процесса) + ok - обновление секретов падает и это видно в логах: 6 событий + ok - перезапущенная реплика без OpenBao не готова: unhealthy running 0 + ok - LB ведёт трафик на живую реплику: {200: 368, 201: 370} + ok - после unseal реплика поднялась сама за 12 c (OpenBao был sealed 86 c) + ok - запросы во время восстановления: {200: 111, 201: 107} + [sealed: 101s] + +17 passed, 0 failed +[exit 0] + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe scripts/lab7.py status + Container mtusi-lab7-pki-run-32d645f6c0c5 Creating + Container mtusi-lab7-pki-run-32d645f6c0c5 Created +lb 28e9b2f37c486e379fc949b3395d06be16ce8083 until 2027-03-02 active (issued 2) +api 50cce6049ba35e64bb5b2106b5c133c6a799e95c until 2027-03-02 active (issued 1) +worker 71cff8f134eae425db3b3de0e761ca63103113f5 until 2027-03-02 active (issued 1) +migrate 37276283a32d29fd2406987fd55cbce32b43557 until 2027-03-02 active (issued 1) +postgres 14872f2539375f9b88b385d9b5828b34fb698c3a until 2027-03-02 active (issued 1) +redis 57141d778043a0730d5967bebf87ddc09f6df1d0 until 2027-03-02 active (issued 1) +broker 56e54961655e27efc3c5bbf9fa0c83ca76628b until 2027-03-02 active (issued 1) +s3 522ba07b9c4d349ec1cfda09813f10ae999f63c3 until 2027-03-02 active (issued 1) +openbao 4f460ed62fba96cfb4c074266c9cd3a461017e4 until 2027-03-02 active (issued 1) +otel-gw 293dddb23f7adf8e299850aab7083a1995b6b219 until 2027-03-02 active (issued 1) +otel-collector ff0be38903220da32764b2d17747c09472648a8 until 2027-03-02 active (issued 1) +prometheus 493bc67fbda31cacf600ee5921bd4efdab8aefdd until 2027-03-02 active (issued 1) +loki f6cca83aafed85eadeaf489f3ce9f9ce25a1225 until 2027-03-02 active (issued 1) +tempo 5df32da279361c141f39f304c59f5213f208da04 until 2027-03-02 active (issued 1) +grafana 191436396285f645dc555e1767215446deb495ec until 2027-03-02 active (issued 1) +redis-ops 3ac9ff81abb27e41a08f7fb24648a53e3f4b8a72 until 2027-03-02 active (issued 1) +broker-ops 24c5461ebf37f5ae324ebde46b95a635fe5f82bc until 2027-03-02 active (issued 1) +intruder 6c0ac69b9bf575a3f7c5131d216a262bb893f401 until 2027-03-02 active (issued 1) +revoked serials: 1 +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab7-api-1 mtusi-messenger:lab7 "python -m app" api 13 minutes ago Up About a minute (healthy) 8443/tcp +mtusi-lab7-api-2 mtusi-messenger:lab7 "python -m app" api 13 minutes ago Up 3 minutes (healthy) 8443/tcp +mtusi-lab7-broker-1 redis:8.6.8 "docker-entrypoint.s…" broker 15 minutes ago Up 9 minutes (healthy) 6379/tcp +mtusi-lab7-grafana-1 grafana/grafana:11.4.0 "/bin/sh -c 'export …" grafana 13 minutes ago Up 13 minutes 127.0.0.1:3000->3000/tcp +mtusi-lab7-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb 13 minutes ago Up 13 minutes (healthy) 127.0.0.1:8443-8445->8443-8445/tcp +mtusi-lab7-loki-1 grafana/loki:3.3.2 "/usr/bin/loki -conf…" loki 13 minutes ago Up 13 minutes 3100/tcp +mtusi-lab7-openbao-1 openbao/openbao:2.6.4 "bao server -config=…" openbao 29 minutes ago Up 27 minutes (healthy) 8200/tcp +mtusi-lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.111.0 "/otelcol-contrib --…" otel-collector 13 minutes ago Up 13 minutes +mtusi-lab7-otel-gw-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" otel-gw 13 minutes ago Up 13 minutes (healthy) +mtusi-lab7-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 26 minutes ago Up 26 minutes (healthy) 5432/tcp +mtusi-lab7-prometheus-1 prom/prometheus:v2.55.1 "/bin/prometheus --c…" prometheus 13 minutes ago Up 13 minutes (healthy) 9090/tcp +mtusi-lab7-redis-1 redis:8.6.8 "docker-entrypoint.s…" redis 15 minutes ago Up 15 minutes (healthy) 6379/tcp +mtusi-lab7-s3-1 pgsty/minio:RELEASE.2026-08-04T00-00-00Z "/usr/bin/docker-ent…" s3 26 minutes ago Up 26 minutes (healthy) 9000/tcp +mtusi-lab7-tempo-1 grafana/tempo:2.6.1 "/tempo -config.file…" tempo 13 minutes ago Up 13 minutes +mtusi-lab7-worker-1 mtusi-messenger:lab7 "python -m app.worker" worker 13 minutes ago Up 6 minutes (healthy) 8443/tcp +openbao: {'initialized': True, 'sealed': False, 'version': '2.6.4', 'storage_type': 'raft'} + $ docker compose --env-file C:\Users\79152\Desktop\mtusi2026lab7\.env --profile ops run --rm pki list + $ docker compose --env-file C:\Users\79152\Desktop\mtusi2026lab7\.env ps +[exit 0] diff --git a/evidence/s3-private.txt b/evidence/s3-private.txt new file mode 100644 index 00000000..8fd5e66a --- /dev/null +++ b/evidence/s3-private.txt @@ -0,0 +1,20 @@ +# s3-private +# date: 2026-12-03T00:25:01 commit: cbbe525 + +$ docker compose --env-file .env exec -T api python -m app.tools private-check + ok api credentials: PUT staging/ (own prefix) -> 200 + ok anonymous GET object -> 403 + ok anonymous LIST bucket -> 403 + ok anonymous PUT object -> 403 + ok api credentials: PUT originals/ (worker prefix) -> AccessDenied + ok api credentials: PUT variants/ (worker prefix) -> AccessDenied + ok api credentials: GET staging/ (only worker reads) -> AccessDenied + ok api credentials: LIST originals/ -> AccessDenied + ok api credentials: ListBuckets (no foreign buckets) -> only messenger-attachments + ok api credentials: CreateBucket -> AccessDenied + ok api credentials: PutBucketPolicy (make public) -> AccessDenied + ok api credentials: DeleteBucket -> AccessDenied + ok api credentials: DELETE staging/ (own prefix) -> 204 + +13 passed, 0 failed +[exit 0] diff --git a/evidence/scan-pip-audit.txt b/evidence/scan-pip-audit.txt new file mode 100644 index 00000000..03fb4580 --- /dev/null +++ b/evidence/scan-pip-audit.txt @@ -0,0 +1,9 @@ +# scan-pip-audit +# date: 2026-12-03T07:42:19 commit: cbbe525 + +$ docker run --rm --entrypoint sh -v C:\Users\79152\Desktop\mtusi2026lab7\requirements.txt:/tmp/requirements.txt:ro python:3.12.7-slim-bookworm -c pip install -q --root-user-action=ignore pip-audit==2.7.3 >/dev/null && pip-audit -r /tmp/requirements.txt --progress-spinner off; true + +[notice] A new release of pip is available: 24.2 -> 26.3 +[notice] To update, run: pip install --upgrade pip +No known vulnerabilities found +[exit 0] diff --git a/evidence/scan-trivy-app.txt b/evidence/scan-trivy-app.txt new file mode 100644 index 00000000..34c51d27 --- /dev/null +++ b/evidence/scan-trivy-app.txt @@ -0,0 +1,420 @@ +# scan-trivy-app +# date: 2026-12-03T07:43:06 commit: cbbe525 + +$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v mtusi-trivy-cache:/root/.cache/ aquasec/trivy:0.58.1 image --scanners vuln --severity HIGH,CRITICAL --no-progress mtusi-messenger:lab7 +2026-12-03T06:43:07Z INFO [vuln] Vulnerability scanning is enabled +2026-12-03T06:43:12Z WARN Third-party SBOM may lead to inaccurate vulnerability detection +2026-12-03T06:43:12Z WARN Recommend using Trivy to generate SBOMs +2026-12-03T06:43:12Z WARN [sbom] Ignore the OS package as no OS is detected. file_path="usr/local/lib/python3.12/site-packages/pillow-13.0.0.dist-info/sboms/auditwheel.cdx.json" +2026-12-03T06:43:12Z WARN Third-party SBOM may lead to inaccurate vulnerability detection +2026-12-03T06:43:12Z WARN Recommend using Trivy to generate SBOMs +2026-12-03T06:43:12Z WARN [sbom] Ignore the OS package as no OS is detected. file_path="usr/local/lib/python3.12/site-packages/psycopg_binary-3.3.6.dist-info/sboms/auditwheel.cdx.json" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="boto3" version="1.38.0" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="botocore" version="1.38.0" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="certifi" version="2026.11.20" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="h11" version="0.16.0" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="jmespath" version="1.1.0" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="python-dateutil" version="2.9.0.post0" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="PyYAML" version="6.0.4" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="requests" version="2.34.2" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="s3transfer" version="0.12.0" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="six" version="1.17.0" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="uvloop" version="0.23.0" +2026-12-03T06:43:13Z INFO [python] License acquired from METADATA classifiers may be subject to additional terms name="watchfiles" version="1.3.0" +2026-12-03T06:43:13Z INFO Detected OS family="debian" version="12.15" +2026-12-03T06:43:13Z INFO [debian] Detecting vulnerabilities... os_version="12" pkg_num=105 +2026-12-03T06:43:13Z INFO Number of language-specific files num=1 +2026-12-03T06:43:13Z INFO [python-pkg] Detecting vulnerabilities... +2026-12-03T06:43:13Z WARN Using severities from other vendors for some vulnerabilities. Read https://aquasecurity.github.io/trivy/v0.58/docs/scanner/vulnerability#severity-selection for details. + +mtusi-messenger:lab7 (debian 12.15) +=================================== +Total: 96 (HIGH: 94, CRITICAL: 2) + +┌──────────────────┬─────────────────┬──────────┬──────────────┬─────────────────────────┬───────────────┬──────────────────────────────────────────────────────────────┐ +│ Library │ Vulnerability │ Severity │ Status │ Installed Version │ Fixed Version │ Title │ +├──────────────────┼─────────────────┼──────────┼──────────────┼─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ bsdutils │ CVE-2026-53613 │ HIGH │ affected │ 1:2.38.1-5+deb12u3 │ │ util-linux: TOCTOU in the mount program via ancestor │ +│ │ │ │ │ │ │ directory swap on target... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53613 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-53615 │ │ │ │ │ util-linux: util-linux: Partition metadata compromise via │ +│ │ │ │ │ │ │ integer overflow in DOS partition parser... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53615 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-78410 │ │ │ │ │ util-linux: util-linux: restricted bind mounts do not pin │ +│ │ │ │ │ │ │ the source, allowing X-mount.owner/group/mode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-78410 │ +├──────────────────┼─────────────────┤ ├──────────────┼─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ gzip │ CVE-2026-41992 │ │ fix_deferred │ 1.12-1 │ │ gzip: gzip: Information disclosure via global buffer │ +│ │ │ │ │ │ │ overflow in LZH decompression │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-41992 │ +├──────────────────┼─────────────────┤ │ ├─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ libacl1 │ CVE-2026-54369 │ │ │ 2.3.1-3 │ │ acl: Symlink traversal privilege escalation via libacl │ +│ │ │ │ │ │ │ functions │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-54369 │ +├──────────────────┼─────────────────┤ ├──────────────┼─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ libblkid1 │ CVE-2026-53613 │ │ affected │ 2.38.1-5+deb12u3 │ │ util-linux: TOCTOU in the mount program via ancestor │ +│ │ │ │ │ │ │ directory swap on target... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53613 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-53615 │ │ │ │ │ util-linux: util-linux: Partition metadata compromise via │ +│ │ │ │ │ │ │ integer overflow in DOS partition parser... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53615 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-78410 │ │ │ │ │ util-linux: util-linux: restricted bind mounts do not pin │ +│ │ │ │ │ │ │ the source, allowing X-mount.owner/group/mode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-78410 │ +├──────────────────┼─────────────────┤ │ ├─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ libgssapi-krb5-2 │ CVE-2026-107364 │ │ │ 1.20.1-2+deb12u5 │ │ krb5: Unauthenticated KDC DoS based on ASN.1 decoder read │ +│ │ │ │ │ │ │ overrun │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-107364 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112315 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS in │ +│ │ │ │ │ │ │ RPCSEC_GSS buffer decode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112315 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112316 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated memory leak DoS in │ +│ │ │ │ │ │ │ xdr_krb5_tl_data() decode failure... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112316 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112317 │ │ │ │ │ krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB │ +│ │ │ │ │ │ │ keytab key... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112317 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112318 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated DoS exploiting │ +│ │ │ │ │ │ │ dereference of null policy name... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112318 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112319 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated memory exhaustion DoS │ +│ │ │ │ │ │ │ via unbounded RPC XDR... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112319 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112320 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS via │ +│ │ │ │ │ │ │ GSS-RPC auth flavor... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112320 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112321 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS via │ +│ │ │ │ │ │ │ AUTH_GSSAPI_INIT error paths... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112321 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112322 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated CPU DoS via │ +│ │ │ │ │ │ │ AUTH_GSSAPI client states cleanup... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112322 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112323 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory exhaustion via │ +│ │ │ │ │ │ │ failed AUTH_GSSAPI_INIT requests │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112323 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-118380 │ │ │ │ │ krb5: kadmind: request alteration and protected information │ +│ │ │ │ │ │ │ disclosure │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-118380 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-119079 │ │ │ │ │ krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic │ +│ │ │ │ │ │ │ ASN.1 SEQUENCE OF... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-119079 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-71199 │ │ │ │ │ krb5: Alteration of authentication indicators in CAMMAC │ +│ │ │ │ │ │ │ container │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-71199 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-71200 │ │ │ │ │ krb5: Unauthenticated KDC NULL pointer dereference KDC DoS │ +│ │ │ │ │ │ │ via crafted PKINIT pre-auth... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-71200 │ +├──────────────────┼─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ libk5crypto3 │ CVE-2026-107364 │ │ │ │ │ krb5: Unauthenticated KDC DoS based on ASN.1 decoder read │ +│ │ │ │ │ │ │ overrun │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-107364 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112315 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS in │ +│ │ │ │ │ │ │ RPCSEC_GSS buffer decode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112315 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112316 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated memory leak DoS in │ +│ │ │ │ │ │ │ xdr_krb5_tl_data() decode failure... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112316 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112317 │ │ │ │ │ krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB │ +│ │ │ │ │ │ │ keytab key... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112317 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112318 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated DoS exploiting │ +│ │ │ │ │ │ │ dereference of null policy name... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112318 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112319 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated memory exhaustion DoS │ +│ │ │ │ │ │ │ via unbounded RPC XDR... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112319 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112320 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS via │ +│ │ │ │ │ │ │ GSS-RPC auth flavor... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112320 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112321 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS via │ +│ │ │ │ │ │ │ AUTH_GSSAPI_INIT error paths... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112321 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112322 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated CPU DoS via │ +│ │ │ │ │ │ │ AUTH_GSSAPI client states cleanup... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112322 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112323 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory exhaustion via │ +│ │ │ │ │ │ │ failed AUTH_GSSAPI_INIT requests │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112323 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-118380 │ │ │ │ │ krb5: kadmind: request alteration and protected information │ +│ │ │ │ │ │ │ disclosure │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-118380 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-119079 │ │ │ │ │ krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic │ +│ │ │ │ │ │ │ ASN.1 SEQUENCE OF... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-119079 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-71199 │ │ │ │ │ krb5: Alteration of authentication indicators in CAMMAC │ +│ │ │ │ │ │ │ container │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-71199 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-71200 │ │ │ │ │ krb5: Unauthenticated KDC NULL pointer dereference KDC DoS │ +│ │ │ │ │ │ │ via crafted PKINIT pre-auth... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-71200 │ +├──────────────────┼─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ libkrb5-3 │ CVE-2026-107364 │ │ │ │ │ krb5: Unauthenticated KDC DoS based on ASN.1 decoder read │ +│ │ │ │ │ │ │ overrun │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-107364 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112315 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS in │ +│ │ │ │ │ │ │ RPCSEC_GSS buffer decode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112315 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112316 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated memory leak DoS in │ +│ │ │ │ │ │ │ xdr_krb5_tl_data() decode failure... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112316 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112317 │ │ │ │ │ krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB │ +│ │ │ │ │ │ │ keytab key... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112317 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112318 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated DoS exploiting │ +│ │ │ │ │ │ │ dereference of null policy name... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112318 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112319 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated memory exhaustion DoS │ +│ │ │ │ │ │ │ via unbounded RPC XDR... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112319 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112320 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS via │ +│ │ │ │ │ │ │ GSS-RPC auth flavor... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112320 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112321 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS via │ +│ │ │ │ │ │ │ AUTH_GSSAPI_INIT error paths... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112321 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112322 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated CPU DoS via │ +│ │ │ │ │ │ │ AUTH_GSSAPI client states cleanup... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112322 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112323 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory exhaustion via │ +│ │ │ │ │ │ │ failed AUTH_GSSAPI_INIT requests │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112323 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-118380 │ │ │ │ │ krb5: kadmind: request alteration and protected information │ +│ │ │ │ │ │ │ disclosure │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-118380 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-119079 │ │ │ │ │ krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic │ +│ │ │ │ │ │ │ ASN.1 SEQUENCE OF... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-119079 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-71199 │ │ │ │ │ krb5: Alteration of authentication indicators in CAMMAC │ +│ │ │ │ │ │ │ container │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-71199 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-71200 │ │ │ │ │ krb5: Unauthenticated KDC NULL pointer dereference KDC DoS │ +│ │ │ │ │ │ │ via crafted PKINIT pre-auth... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-71200 │ +├──────────────────┼─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ libkrb5support0 │ CVE-2026-107364 │ │ │ │ │ krb5: Unauthenticated KDC DoS based on ASN.1 decoder read │ +│ │ │ │ │ │ │ overrun │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-107364 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112315 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS in │ +│ │ │ │ │ │ │ RPCSEC_GSS buffer decode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112315 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112316 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated memory leak DoS in │ +│ │ │ │ │ │ │ xdr_krb5_tl_data() decode failure... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112316 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112317 │ │ │ │ │ krb5: MIT krb5 KDC unauthenticated memory leak DoS in KDB │ +│ │ │ │ │ │ │ keytab key... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112317 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112318 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated DoS exploiting │ +│ │ │ │ │ │ │ dereference of null policy name... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112318 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112319 │ │ │ │ │ krb5: MIT krb5 kadmind authenticated memory exhaustion DoS │ +│ │ │ │ │ │ │ via unbounded RPC XDR... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112319 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112320 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS via │ +│ │ │ │ │ │ │ GSS-RPC auth flavor... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112320 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112321 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory leak DoS via │ +│ │ │ │ │ │ │ AUTH_GSSAPI_INIT error paths... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112321 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112322 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated CPU DoS via │ +│ │ │ │ │ │ │ AUTH_GSSAPI client states cleanup... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112322 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-112323 │ │ │ │ │ krb5: MIT krb5 kadmind unauthenticated memory exhaustion via │ +│ │ │ │ │ │ │ failed AUTH_GSSAPI_INIT requests │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-112323 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-118380 │ │ │ │ │ krb5: kadmind: request alteration and protected information │ +│ │ │ │ │ │ │ disclosure │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-118380 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-119079 │ │ │ │ │ krb5: MIT krb5 KDC unauthenticated CPU DoS via quadratic │ +│ │ │ │ │ │ │ ASN.1 SEQUENCE OF... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-119079 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-71199 │ │ │ │ │ krb5: Alteration of authentication indicators in CAMMAC │ +│ │ │ │ │ │ │ container │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-71199 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-71200 │ │ │ │ │ krb5: Unauthenticated KDC NULL pointer dereference KDC DoS │ +│ │ │ │ │ │ │ via crafted PKINIT pre-auth... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-71200 │ +├──────────────────┼─────────────────┤ │ ├─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ libmount1 │ CVE-2026-53613 │ │ │ 2.38.1-5+deb12u3 │ │ util-linux: TOCTOU in the mount program via ancestor │ +│ │ │ │ │ │ │ directory swap on target... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53613 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-53615 │ │ │ │ │ util-linux: util-linux: Partition metadata compromise via │ +│ │ │ │ │ │ │ integer overflow in DOS partition parser... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53615 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-78410 │ │ │ │ │ util-linux: util-linux: restricted bind mounts do not pin │ +│ │ │ │ │ │ │ the source, allowing X-mount.owner/group/mode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-78410 │ +├──────────────────┼─────────────────┤ │ ├─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ libncursesw6 │ CVE-2025-69720 │ │ │ 6.4-4 │ │ ncurses: ncurses: Buffer overflow vulnerability may lead to │ +│ │ │ │ │ │ │ arbitrary code execution. │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2025-69720 │ +├──────────────────┼─────────────────┤ │ ├─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ libsmartcols1 │ CVE-2026-53613 │ │ │ 2.38.1-5+deb12u3 │ │ util-linux: TOCTOU in the mount program via ancestor │ +│ │ │ │ │ │ │ directory swap on target... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53613 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-53615 │ │ │ │ │ util-linux: util-linux: Partition metadata compromise via │ +│ │ │ │ │ │ │ integer overflow in DOS partition parser... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53615 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-78410 │ │ │ │ │ util-linux: util-linux: restricted bind mounts do not pin │ +│ │ │ │ │ │ │ the source, allowing X-mount.owner/group/mode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-78410 │ +├──────────────────┼─────────────────┼──────────┤ ├─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ libsqlite3-0 │ CVE-2025-7458 │ CRITICAL │ │ 3.40.1-2+deb12u2 │ │ sqlite: SQLite integer overflow │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2025-7458 │ +│ ├─────────────────┼──────────┼──────────────┤ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-11822 │ HIGH │ fix_deferred │ │ │ sqlite: SQLite: Arbitrary code execution via crafted FTS5 │ +│ │ │ │ │ │ │ full-text search data │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-11822 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-11824 │ │ │ │ │ sqlite: SQLite: Arbitrary code execution and crash via │ +│ │ │ │ │ │ │ heap-based buffer overflow in... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-11824 │ +│ ├─────────────────┤ ├──────────────┤ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-119373 │ │ affected │ │ │ sqlite: sqlite: Denial of service via heap-based buffer │ +│ │ │ │ │ │ │ overflow in FTS5 │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-119373 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-119374 │ │ │ │ │ sqlite: sqlite: Arbitrary code execution via corrupted FTS5 │ +│ │ │ │ │ │ │ index │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-119374 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-119379 │ │ │ │ │ sqlite: sqlite: Arbitrary code execution via crafted session │ +│ │ │ │ │ │ │ changesets │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-119379 │ +├──────────────────┼─────────────────┤ ├──────────────┼─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ libsystemd0 │ CVE-2026-16742 │ │ fix_deferred │ 252.39-1~deb12u2 │ │ systemd: systemd-homed: Local privilege escalation via │ +│ │ │ │ │ │ │ missing home-record signature verification │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-16742 │ +├──────────────────┼─────────────────┤ ├──────────────┼─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ libtinfo6 │ CVE-2025-69720 │ │ affected │ 6.4-4 │ │ ncurses: ncurses: Buffer overflow vulnerability may lead to │ +│ │ │ │ │ │ │ arbitrary code execution. │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2025-69720 │ +├──────────────────┼─────────────────┤ ├──────────────┼─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ libudev1 │ CVE-2026-16742 │ │ fix_deferred │ 252.39-1~deb12u2 │ │ systemd: systemd-homed: Local privilege escalation via │ +│ │ │ │ │ │ │ missing home-record signature verification │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-16742 │ +├──────────────────┼─────────────────┤ ├──────────────┼─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ libuuid1 │ CVE-2026-53613 │ │ affected │ 2.38.1-5+deb12u3 │ │ util-linux: TOCTOU in the mount program via ancestor │ +│ │ │ │ │ │ │ directory swap on target... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53613 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-53615 │ │ │ │ │ util-linux: util-linux: Partition metadata compromise via │ +│ │ │ │ │ │ │ integer overflow in DOS partition parser... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53615 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-78410 │ │ │ │ │ util-linux: util-linux: restricted bind mounts do not pin │ +│ │ │ │ │ │ │ the source, allowing X-mount.owner/group/mode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-78410 │ +├──────────────────┼─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ mount │ CVE-2026-53613 │ │ │ │ │ util-linux: TOCTOU in the mount program via ancestor │ +│ │ │ │ │ │ │ directory swap on target... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53613 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-53615 │ │ │ │ │ util-linux: util-linux: Partition metadata compromise via │ +│ │ │ │ │ │ │ integer overflow in DOS partition parser... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53615 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-78410 │ │ │ │ │ util-linux: util-linux: restricted bind mounts do not pin │ +│ │ │ │ │ │ │ the source, allowing X-mount.owner/group/mode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-78410 │ +├──────────────────┼─────────────────┤ │ ├─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ ncurses-base │ CVE-2025-69720 │ │ │ 6.4-4 │ │ ncurses: ncurses: Buffer overflow vulnerability may lead to │ +│ │ │ │ │ │ │ arbitrary code execution. │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2025-69720 │ +├──────────────────┤ │ │ │ ├───────────────┤ │ +│ ncurses-bin │ │ │ │ │ │ │ +│ │ │ │ │ │ │ │ +│ │ │ │ │ │ │ │ +├──────────────────┼─────────────────┤ ├──────────────┼─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ perl-base │ CVE-2026-9538 │ │ fix_deferred │ 5.36.0-7+deb12u4 │ │ perl-Archive-Tar: perl-Archive-Tar: Denial of Service via │ +│ │ │ │ │ │ │ crafted tar header with large entry... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-9538 │ +├──────────────────┼─────────────────┤ ├──────────────┼─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ util-linux │ CVE-2026-53613 │ │ affected │ 2.38.1-5+deb12u3 │ │ util-linux: TOCTOU in the mount program via ancestor │ +│ │ │ │ │ │ │ directory swap on target... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53613 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-53615 │ │ │ │ │ util-linux: util-linux: Partition metadata compromise via │ +│ │ │ │ │ │ │ integer overflow in DOS partition parser... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53615 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-78410 │ │ │ │ │ util-linux: util-linux: restricted bind mounts do not pin │ +│ │ │ │ │ │ │ the source, allowing X-mount.owner/group/mode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-78410 │ +├──────────────────┼─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ util-linux-extra │ CVE-2026-53613 │ │ │ │ │ util-linux: TOCTOU in the mount program via ancestor │ +│ │ │ │ │ │ │ directory swap on target... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53613 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-53615 │ │ │ │ │ util-linux: util-linux: Partition metadata compromise via │ +│ │ │ │ │ │ │ integer overflow in DOS partition parser... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-53615 │ +│ ├─────────────────┤ │ │ ├───────────────┼──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-78410 │ │ │ │ │ util-linux: util-linux: restricted bind mounts do not pin │ +│ │ │ │ │ │ │ the source, allowing X-mount.owner/group/mode... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-78410 │ +├──────────────────┼─────────────────┼──────────┼──────────────┼─────────────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ zlib1g │ CVE-2023-45853 │ CRITICAL │ will_not_fix │ 1:1.2.13.dfsg-1+deb12u1 │ │ zlib: integer overflow and resultant heap-based buffer │ +│ │ │ │ │ │ │ overflow in zipOpenNewFileInZip4_6 │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2023-45853 │ +└──────────────────┴─────────────────┴──────────┴──────────────┴─────────────────────────┴───────────────┴──────────────────────────────────────────────────────────────┘ +[exit 0] diff --git a/evidence/scan-trivy-infra.txt b/evidence/scan-trivy-infra.txt new file mode 100644 index 00000000..6cc1afc6 --- /dev/null +++ b/evidence/scan-trivy-infra.txt @@ -0,0 +1,226 @@ +# scan-trivy-infra +# date: 2026-12-03T00:38:16 commit: cbbe525 + +$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v mtusi-trivy-cache:/root/.cache/ aquasec/trivy:0.58.1 image --scanners vuln --severity CRITICAL --no-progress postgres:16.4-alpine +2026-12-02T23:38:16Z INFO [vuln] Vulnerability scanning is enabled +2026-12-02T23:38:23Z INFO Detected OS family="alpine" version="3.20.3" +2026-12-02T23:38:23Z INFO [alpine] Detecting vulnerabilities... os_version="3.20" repository="3.20" pkg_num=45 +2026-12-02T23:38:23Z INFO Number of language-specific files num=1 +2026-12-02T23:38:23Z INFO [gobinary] Detecting vulnerabilities... +2026-12-02T23:38:23Z WARN Using severities from other vendors for some vulnerabilities. Read https://aquasecurity.github.io/trivy/v0.58/docs/scanner/vulnerability#severity-selection for details. +2026-12-02T23:38:23Z WARN This OS version is no longer supported by the distribution family="alpine" version="3.20.3" +2026-12-02T23:38:23Z WARN The vulnerability detection may be insufficient because security updates are not provided + +postgres:16.4-alpine (alpine 3.20.3) +==================================== +Total: 3 (CRITICAL: 3) + +┌────────────┬────────────────┬──────────┬────────┬───────────────────┬───────────────┬──────────────────────────────────────────────────────────┐ +│ Library │ Vulnerability │ Severity │ Status │ Installed Version │ Fixed Version │ Title │ +├────────────┼────────────────┼──────────┼────────┼───────────────────┼───────────────┼──────────────────────────────────────────────────────────┤ +│ libcrypto3 │ CVE-2026-31789 │ CRITICAL │ fixed │ 3.3.2-r1 │ 3.3.7-r0 │ openssl: OpenSSL: Heap buffer overflow on 32-bit systems │ +│ │ │ │ │ │ │ from large X.509 certificate... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-31789 │ +├────────────┤ │ │ │ │ │ │ +│ libssl3 │ │ │ │ │ │ │ +│ │ │ │ │ │ │ │ +│ │ │ │ │ │ │ │ +├────────────┼────────────────┤ │ ├───────────────────┼───────────────┼──────────────────────────────────────────────────────────┤ +│ libxml2 │ CVE-2024-56171 │ │ │ 2.12.7-r0 │ 2.12.7-r1 │ libxml2: Use-After-Free in libxml2 │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2024-56171 │ +└────────────┴────────────────┴──────────┴────────┴───────────────────┴───────────────┴──────────────────────────────────────────────────────────┘ + +usr/local/bin/gosu (gobinary) +============================= +Total: 4 (CRITICAL: 4) + +┌─────────┬────────────────┬──────────┬────────┬───────────────────┬──────────────────────────────┬────────────────────────────────────────────────────────────┐ +│ Library │ Vulnerability │ Severity │ Status │ Installed Version │ Fixed Version │ Title │ +├─────────┼────────────────┼──────────┼────────┼───────────────────┼──────────────────────────────┼────────────────────────────────────────────────────────────┤ +│ stdlib │ CVE-2023-24538 │ CRITICAL │ fixed │ v1.18.2 │ 1.19.8, 1.20.3 │ golang: html/template: backticks not treated as string │ +│ │ │ │ │ │ │ delimiters │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2023-24538 │ +│ ├────────────────┤ │ │ ├──────────────────────────────┼────────────────────────────────────────────────────────────┤ +│ │ CVE-2023-24540 │ │ │ │ 1.19.9, 1.20.4 │ golang: html/template: improper handling of JavaScript │ +│ │ │ │ │ │ │ whitespace │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2023-24540 │ +│ ├────────────────┤ │ │ ├──────────────────────────────┼────────────────────────────────────────────────────────────┤ +│ │ CVE-2024-24790 │ │ │ │ 1.21.11, 1.22.4 │ golang: net/netip: Unexpected behavior from Is methods for │ +│ │ │ │ │ │ │ IPv4-mapped IPv6 addresses │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2024-24790 │ +│ ├────────────────┤ │ │ ├──────────────────────────────┼────────────────────────────────────────────────────────────┤ +│ │ CVE-2025-68121 │ │ │ │ 1.24.13, 1.25.7, 1.26.0-rc.3 │ crypto/tls: crypto/tls: Incorrect certificate validation │ +│ │ │ │ │ │ │ during TLS session resumption │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2025-68121 │ +└─────────┴────────────────┴──────────┴────────┴───────────────────┴──────────────────────────────┴────────────────────────────────────────────────────────────┘ +[exit 0] + +$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v mtusi-trivy-cache:/root/.cache/ aquasec/trivy:0.58.1 image --scanners vuln --severity CRITICAL --no-progress redis:8.6.8 +2026-12-02T23:38:24Z INFO [vuln] Vulnerability scanning is enabled +2026-12-02T23:38:28Z INFO Detected OS family="debian" version="13.8" +2026-12-02T23:38:28Z INFO [debian] Detecting vulnerabilities... os_version="13" pkg_num=78 +2026-12-02T23:38:28Z INFO Number of language-specific files num=0 +2026-12-02T23:38:28Z WARN Using severities from other vendors for some vulnerabilities. Read https://aquasecurity.github.io/trivy/v0.58/docs/scanner/vulnerability#severity-selection for details. + +redis:8.6.8 (debian 13.8) +========================= +Total: 0 (CRITICAL: 0) + +[exit 0] + +$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v mtusi-trivy-cache:/root/.cache/ aquasec/trivy:0.58.1 image --scanners vuln --severity CRITICAL --no-progress openbao/openbao:2.6.4 +2026-12-02T23:38:29Z INFO [vuln] Vulnerability scanning is enabled +2026-12-02T23:38:34Z INFO Detected OS family="alpine" version="3.24.2" +2026-12-02T23:38:34Z WARN This OS version is not on the EOL list family="alpine" version="3.24" +2026-12-02T23:38:34Z INFO [alpine] Detecting vulnerabilities... os_version="3.24" repository="3.24" pkg_num=28 +2026-12-02T23:38:34Z INFO Number of language-specific files num=1 +2026-12-02T23:38:34Z INFO [gobinary] Detecting vulnerabilities... +2026-12-02T23:38:34Z WARN Using severities from other vendors for some vulnerabilities. Read https://aquasecurity.github.io/trivy/v0.58/docs/scanner/vulnerability#severity-selection for details. + +openbao/openbao:2.6.4 (alpine 3.24.2) +===================================== +Total: 0 (CRITICAL: 0) + +[exit 0] + +$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v mtusi-trivy-cache:/root/.cache/ aquasec/trivy:0.58.1 image --scanners vuln --severity CRITICAL --no-progress haproxy:3.0.5-alpine +2026-12-02T23:38:35Z INFO [vuln] Vulnerability scanning is enabled +2026-12-02T23:38:37Z INFO Detected OS family="alpine" version="3.20.3" +2026-12-02T23:38:37Z INFO [alpine] Detecting vulnerabilities... os_version="3.20" repository="3.20" pkg_num=18 +2026-12-02T23:38:37Z INFO Number of language-specific files num=0 +2026-12-02T23:38:37Z WARN Using severities from other vendors for some vulnerabilities. Read https://aquasecurity.github.io/trivy/v0.58/docs/scanner/vulnerability#severity-selection for details. +2026-12-02T23:38:37Z WARN This OS version is no longer supported by the distribution family="alpine" version="3.20.3" +2026-12-02T23:38:37Z WARN The vulnerability detection may be insufficient because security updates are not provided + +haproxy:3.0.5-alpine (alpine 3.20.3) +==================================== +Total: 2 (CRITICAL: 2) + +┌────────────┬────────────────┬──────────┬────────┬───────────────────┬───────────────┬──────────────────────────────────────────────────────────┐ +│ Library │ Vulnerability │ Severity │ Status │ Installed Version │ Fixed Version │ Title │ +├────────────┼────────────────┼──────────┼────────┼───────────────────┼───────────────┼──────────────────────────────────────────────────────────┤ +│ libcrypto3 │ CVE-2026-31789 │ CRITICAL │ fixed │ 3.3.2-r0 │ 3.3.7-r0 │ openssl: OpenSSL: Heap buffer overflow on 32-bit systems │ +│ │ │ │ │ │ │ from large X.509 certificate... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-31789 │ +├────────────┤ │ │ │ │ │ │ +│ libssl3 │ │ │ │ │ │ │ +│ │ │ │ │ │ │ │ +│ │ │ │ │ │ │ │ +└────────────┴────────────────┴──────────┴────────┴───────────────────┴───────────────┴──────────────────────────────────────────────────────────┘ +[exit 0] + +$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v mtusi-trivy-cache:/root/.cache/ aquasec/trivy:0.58.1 image --scanners vuln --severity CRITICAL --no-progress pgsty/minio:RELEASE.2026-08-04T00-00-00Z +2026-12-02T23:38:38Z INFO [vuln] Vulnerability scanning is enabled +2026-12-02T23:38:41Z INFO Detected OS family="redhat" version="9.8" +2026-12-02T23:38:41Z INFO [redhat] Detecting RHEL/CentOS vulnerabilities... os_version="9" pkg_num=20 +2026-12-02T23:38:41Z INFO Number of language-specific files num=2 +2026-12-02T23:38:41Z INFO [gobinary] Detecting vulnerabilities... +2026-12-02T23:38:41Z WARN Using severities from other vendors for some vulnerabilities. Read https://aquasecurity.github.io/trivy/v0.58/docs/scanner/vulnerability#severity-selection for details. + +pgsty/minio:RELEASE.2026-08-04T00-00-00Z (redhat 9.8) +===================================================== +Total: 0 (CRITICAL: 0) + + +usr/bin/minio (gobinary) +======================== +Total: 3 (CRITICAL: 3) + +┌────────────────────────────────┬────────────────┬──────────┬────────┬───────────────────┬───────────────┬──────────────────────────────────────────────────────────────┐ +│ Library │ Vulnerability │ Severity │ Status │ Installed Version │ Fixed Version │ Title │ +├────────────────────────────────┼────────────────┼──────────┼────────┼───────────────────┼───────────────┼──────────────────────────────────────────────────────────────┤ +│ github.com/rabbitmq/amqp091-go │ CVE-2026-77405 │ CRITICAL │ fixed │ v1.10.0 │ 1.13.0 │ github.com/rabbitmq/amqp091-go: RabbitMQ amqp091-go: Missing │ +│ │ │ │ │ │ │ Explicit TLS Minimum Version Configuration In URI Parser... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-77405 │ +│ ├────────────────┤ │ │ │ ├──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-77408 │ │ │ │ │ github.com/rabbitmq/amqp091-go: RabbitMQ amqp091-go: Silent │ +│ │ │ │ │ │ │ Data Truncation and State Corruption via Shortstr Integer... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-77408 │ +│ ├────────────────┤ │ │ │ ├──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-77411 │ │ │ │ │ github.com/rabbitmq/amqp091-go: RabbitMQ amqp091-go: │ +│ │ │ │ │ │ │ Protocol Desynchronization and Frame Injection via Integer │ +│ │ │ │ │ │ │ Overflow in... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-77411 │ +└────────────────────────────────┴────────────────┴──────────┴────────┴───────────────────┴───────────────┴──────────────────────────────────────────────────────────────┘ +[exit 0] + +$ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v mtusi-trivy-cache:/root/.cache/ aquasec/trivy:0.58.1 image --scanners vuln --severity CRITICAL --no-progress grafana/grafana:11.4.0 +2026-12-02T23:38:42Z INFO [vuln] Vulnerability scanning is enabled +2026-12-02T23:38:49Z INFO Detected OS family="alpine" version="3.20.3" +2026-12-02T23:38:49Z INFO [alpine] Detecting vulnerabilities... os_version="3.20" repository="3.20" pkg_num=35 +2026-12-02T23:38:49Z INFO Number of language-specific files num=4 +2026-12-02T23:38:49Z INFO [gobinary] Detecting vulnerabilities... +2026-12-02T23:38:49Z INFO [node-pkg] Detecting vulnerabilities... +2026-12-02T23:38:49Z WARN Using severities from other vendors for some vulnerabilities. Read https://aquasecurity.github.io/trivy/v0.58/docs/scanner/vulnerability#severity-selection for details. +2026-12-02T23:38:49Z WARN This OS version is no longer supported by the distribution family="alpine" version="3.20.3" +2026-12-02T23:38:49Z WARN The vulnerability detection may be insufficient because security updates are not provided + +grafana/grafana:11.4.0 (alpine 3.20.3) +====================================== +Total: 2 (CRITICAL: 2) + +┌────────────┬────────────────┬──────────┬────────┬───────────────────┬───────────────┬──────────────────────────────────────────────────────────┐ +│ Library │ Vulnerability │ Severity │ Status │ Installed Version │ Fixed Version │ Title │ +├────────────┼────────────────┼──────────┼────────┼───────────────────┼───────────────┼──────────────────────────────────────────────────────────┤ +│ libcrypto3 │ CVE-2026-31789 │ CRITICAL │ fixed │ 3.3.2-r0 │ 3.3.7-r0 │ openssl: OpenSSL: Heap buffer overflow on 32-bit systems │ +│ │ │ │ │ │ │ from large X.509 certificate... │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-31789 │ +├────────────┤ │ │ │ │ │ │ +│ libssl3 │ │ │ │ │ │ │ +│ │ │ │ │ │ │ │ +│ │ │ │ │ │ │ │ +└────────────┴────────────────┴──────────┴────────┴───────────────────┴───────────────┴──────────────────────────────────────────────────────────┘ + +usr/share/grafana/bin/grafana (gobinary) +======================================== +Total: 5 (CRITICAL: 5) + +┌───────────────────────────────┬─────────────────────┬──────────┬────────┬───────────────────┬──────────────────────────────┬──────────────────────────────────────────────────────────────┐ +│ Library │ Vulnerability │ Severity │ Status │ Installed Version │ Fixed Version │ Title │ +├───────────────────────────────┼─────────────────────┼──────────┼────────┼───────────────────┼──────────────────────────────┼──────────────────────────────────────────────────────────────┤ +│ github.com/getkin/kin-openapi │ GHSA-r277-6w6q-xmqw │ CRITICAL │ fixed │ v0.125.0 │ 0.144.0 │ kin-openapi: ValidationHandler.Load() Fail-Open │ +│ │ │ │ │ │ │ Authentication Bypass via NoopAuthenticationFunc Default │ +│ │ │ │ │ │ │ https://github.com/advisories/GHSA-r277-6w6q-xmqw │ +├───────────────────────────────┼─────────────────────┤ │ ├───────────────────┼──────────────────────────────┼──────────────────────────────────────────────────────────────┤ +│ github.com/jackc/pgx/v5 │ CVE-2026-33815 │ │ │ v5.5.5 │ 5.9.0 │ github.com/jackc/pgx/v5: github.com/jackc/pgx: Memory-safety │ +│ │ │ │ │ │ │ vulnerability │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-33815 │ +│ ├─────────────────────┤ │ │ │ ├──────────────────────────────────────────────────────────────┤ +│ │ CVE-2026-33816 │ │ │ │ │ github.com/jackc/pgx/v5: github.com/jackc/pgx: Memory-safety │ +│ │ │ │ │ │ │ vulnerability │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-33816 │ +├───────────────────────────────┼─────────────────────┤ │ ├───────────────────┼──────────────────────────────┼──────────────────────────────────────────────────────────────┤ +│ google.golang.org/grpc │ CVE-2026-33186 │ │ │ v1.66.0 │ 1.79.3 │ google.golang.org/grpc/grpc-go: │ +│ │ │ │ │ │ │ google.golang.org/grpc/authz: gRPC-Go: Authorization bypass │ +│ │ │ │ │ │ │ due to improper HTTP/2 path validation │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2026-33186 │ +├───────────────────────────────┼─────────────────────┤ │ ├───────────────────┼──────────────────────────────┼──────────────────────────────────────────────────────────────┤ +│ stdlib │ CVE-2025-68121 │ │ │ v1.23.1 │ 1.24.13, 1.25.7, 1.26.0-rc.3 │ crypto/tls: crypto/tls: Incorrect certificate validation │ +│ │ │ │ │ │ │ during TLS session resumption │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2025-68121 │ +└───────────────────────────────┴─────────────────────┴──────────┴────────┴───────────────────┴──────────────────────────────┴──────────────────────────────────────────────────────────────┘ + +usr/share/grafana/bin/grafana-cli (gobinary) +============================================ +Total: 1 (CRITICAL: 1) + +┌─────────┬────────────────┬──────────┬────────┬───────────────────┬──────────────────────────────┬──────────────────────────────────────────────────────────┐ +│ Library │ Vulnerability │ Severity │ Status │ Installed Version │ Fixed Version │ Title │ +├─────────┼────────────────┼──────────┼────────┼───────────────────┼──────────────────────────────┼──────────────────────────────────────────────────────────┤ +│ stdlib │ CVE-2025-68121 │ CRITICAL │ fixed │ v1.23.1 │ 1.24.13, 1.25.7, 1.26.0-rc.3 │ crypto/tls: crypto/tls: Incorrect certificate validation │ +│ │ │ │ │ │ │ during TLS session resumption │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2025-68121 │ +└─────────┴────────────────┴──────────┴────────┴───────────────────┴──────────────────────────────┴──────────────────────────────────────────────────────────┘ + +usr/share/grafana/bin/grafana-server (gobinary) +=============================================== +Total: 1 (CRITICAL: 1) + +┌─────────┬────────────────┬──────────┬────────┬───────────────────┬──────────────────────────────┬──────────────────────────────────────────────────────────┐ +│ Library │ Vulnerability │ Severity │ Status │ Installed Version │ Fixed Version │ Title │ +├─────────┼────────────────┼──────────┼────────┼───────────────────┼──────────────────────────────┼──────────────────────────────────────────────────────────┤ +│ stdlib │ CVE-2025-68121 │ CRITICAL │ fixed │ v1.23.1 │ 1.24.13, 1.25.7, 1.26.0-rc.3 │ crypto/tls: crypto/tls: Incorrect certificate validation │ +│ │ │ │ │ │ │ during TLS session resumption │ +│ │ │ │ │ │ │ https://avd.aquasec.com/nvd/cve-2025-68121 │ +└─────────┴────────────────┴──────────┴────────┴───────────────────┴──────────────────────────────┴──────────────────────────────────────────────────────────┘ +[exit 0] diff --git a/evidence/security-neg.txt b/evidence/security-neg.txt new file mode 100644 index 00000000..eb085256 --- /dev/null +++ b/evidence/security-neg.txt @@ -0,0 +1,81 @@ +# security-neg +# date: 2026-12-03T16:50:58 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/security_neg.py --base-url https://localhost:8443 +== ACL: посторонний пользователь и подмена identity + ok - чат A+B, сообщение и вложение созданы + ok - посторонний: метаданные чата → 404 (404, существование не раскрывается) + ok - посторонний: сообщения чата → 404 (404, существование не раскрывается) + ok - посторонний: метаданные вложения → 404 (404, существование не раскрывается) + ok - посторонний: содержимое вложения → 404 (404, существование не раскрывается) + ok - посторонний: thumbnail вложения → 404 (404, существование не раскрывается) + ok - посторонний прикрепляет чужой файл к своему чату → 404 + ok - X-User-Id чужого пользователя игнорируется (identity из Bearer) + ok - только X-User-Id без Bearer → 401 + ok - поддельный токен → 401 + [acl: 2s] +== Сессии: logout и истечение + ok - logout → 204 + ok - старый токен после logout → 401 + ok - сессия с TTL 2 c: сразу 200, через 3,5 c 401 (истекла) + [session: 18s] +== Общий для реплик лимит входа (Redis): 429 + Retry-After + ok - 5 неверных паролей → [401, 401, 401, 401, 401] + ok - 6-я попытка → 429, Retry-After: 300 + ok - попытки обслуживали разные реплики ['461380a2accf', '8e702d1fefc5'] — счётчик общий + ok - даже верный пароль во время блокировки → 429 (подбор не продолжить) + ok - другой аккаунт с того же адреса входит (лимит IP не исчерпан) + [ratelimit: 0s] +== Ограничение размера тела + ok - сообщение 70 KB (лимит 64 KiB) → 413 + ok - регистрация с телом 100 KB → 413 (до Argon2id не доходит) + [limits: 0s] +== Argon2id: параметры в хэше и rehash при входе + ok - формат PHC: $argon2id$v=19$m=…,t=…,p=…$соль$хэш (соль и параметры хранятся) + ok - параметры m=19456 KiB, t=2, p=1 (≥ 19 MiB, 2, 1) + ok - соль у каждого хэша своя + ok - вход со старым хэшем (m=8192,t=1) → 201 + ok - после входа хэш пересчитан с текущими параметрами (rehash): m=19456,t=2,p=1 + ok - вход после rehash работает + [argon2: 3s] +== Бюджет защиты от дорогих входов (Argon2id) + ok - Argon2id m=19456,t=2,p=1: 75.4 мс на хэш (CPU лимит реплики 0,5) + бюджет: 2 одновременных хэша × 2 реплики / 75.4 мс ≈ 53.1 входов/с всего; очередь 8 на реплику, сверх неё — сразу 429 + ok - 60 одновременных входов: {401: 30, 429: 30}; p95 2075 мс (лишние отклонены сразу, без очереди) + ok - остальной API во время всплеска: GET /users/me медиана 28 мс + [dos: 10s] +== Порты, hardening контейнеров, секреты в образе, изоляция сетей + ok - опубликовано только: 127.0.0.1:3000, 127.0.0.1:8443, 127.0.0.1:8444, 127.0.0.1:8445 + service user ro nnp drop add mem + api appuser T T T 256 MiB + api appuser T T T 256 MiB + broker 999:999 T T T 256 MiB + grafana 472 T T T 384 MiB + lb haproxy T T T 128 MiB + loki 10001 T T T 512 MiB + openbao openbao T T T 256 MiB + otel-collector 10001 T T T 256 MiB + otel-gw haproxy T T T 64 MiB + postgres 70:70 T T T 512 MiB + prometheus nobody T T T 512 MiB + redis 999:999 T T T 96 MiB + s3 root T T T 512 MiB + tempo 10001:10001 T T T 512 MiB + worker appuser T T T 1024 MiB + ok - нет privileged-контейнеров + ok - нет network_mode: host + ok - Docker socket не смонтирован ни в один контейнер + ok - no-new-privileges и cap_drop ALL — у всех + ok - корневая ФС только для чтения — у всех долгоживущих + ok - у всех задан лимит памяти + ok - api/worker — не root (appuser) + root (без capabilities, ФС read-only): s3 + ok - в ENV образа нет паролей/ключей/токенов (переменные: PATH, LANG, GPG_KEY, PYTHON_VERSION, PYTHON_SHA256, PYTHONDONTWRITEBYTECODE, PYTHONUNBUFFERED, APP_HOST, APP_PORT, HEALTH_PORT, SHUTDOWN_TIMEOUT; подозрительные: нет) + ok - в образе нет ключей/сертификатов/.env (публичные корневые CA /etc/ssl/certs не в счёт) + ok - api не видит хранилища telemetry и Grafana: {'loki': 'gaierror', 'prometheus': 'gaierror', 'grafana': 'gaierror'} + ok - api видит только нужное: openbao, postgres + ok - worker не видит LB/внешний вход: lb gaierror + [docker: 2s] + +42 passed, 0 failed +[exit 0] diff --git a/evidence/security.txt b/evidence/security.txt new file mode 100644 index 00000000..2f52fe2d --- /dev/null +++ b/evidence/security.txt @@ -0,0 +1,6 @@ +# security +# date: 2026-12-03T00:23:16 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe tests/security.py --base-url https://localhost:8443 --ca-file C:\Users\79152\Desktop\mtusi2026lab7\secrets\ca.crt +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. +[exit 0] diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..bbcf76f8 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,6 @@ +# smoke +# date: 2026-12-03T16:50:55 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe tests/smoke.py --base-url https://localhost:8443 --ca-file C:\Users\79152\Desktop\mtusi2026lab7\secrets\ca.crt +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. +[exit 0] diff --git a/evidence/stand.txt b/evidence/stand.txt new file mode 100644 index 00000000..0989715a --- /dev/null +++ b/evidence/stand.txt @@ -0,0 +1,83 @@ +# stand +# date: 2026-12-03T00:23:10 commit: cbbe525 + +$ docker compose --env-file .env ps +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab7-api-1 mtusi-messenger:lab7 "python -m app" api About a minute ago Up About a minute (healthy) 8443/tcp +mtusi-lab7-api-2 mtusi-messenger:lab7 "python -m app" api About a minute ago Up About a minute (healthy) 8443/tcp +mtusi-lab7-broker-1 redis:8.6.8 "docker-entrypoint.s…" broker 3 minutes ago Up 3 minutes (healthy) 6379/tcp +mtusi-lab7-grafana-1 grafana/grafana:11.4.0 "/bin/sh -c 'export …" grafana About a minute ago Up About a minute 127.0.0.1:3000->3000/tcp +mtusi-lab7-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb About a minute ago Up About a minute (healthy) 127.0.0.1:8443-8445->8443-8445/tcp +mtusi-lab7-loki-1 grafana/loki:3.3.2 "/usr/bin/loki -conf…" loki About a minute ago Up About a minute 3100/tcp +mtusi-lab7-openbao-1 openbao/openbao:2.6.4 "bao server -config=…" openbao 17 minutes ago Up 15 minutes (healthy) 8200/tcp +mtusi-lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.111.0 "/otelcol-contrib --…" otel-collector About a minute ago Up About a minute +mtusi-lab7-otel-gw-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" otel-gw About a minute ago Up About a minute (healthy) +mtusi-lab7-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 14 minutes ago Up 14 minutes (healthy) 5432/tcp +mtusi-lab7-prometheus-1 prom/prometheus:v2.55.1 "/bin/prometheus --c…" prometheus About a minute ago Up About a minute (healthy) 9090/tcp +mtusi-lab7-redis-1 redis:8.6.8 "docker-entrypoint.s…" redis 3 minutes ago Up 3 minutes (healthy) 6379/tcp +mtusi-lab7-s3-1 pgsty/minio:RELEASE.2026-08-04T00-00-00Z "/usr/bin/docker-ent…" s3 14 minutes ago Up 14 minutes (healthy) 9000/tcp +mtusi-lab7-tempo-1 grafana/tempo:2.6.1 "/tempo -config.file…" tempo About a minute ago Up About a minute +mtusi-lab7-worker-1 mtusi-messenger:lab7 "python -m app.worker" worker About a minute ago Up About a minute (healthy) 8443/tcp +[exit 0] + +$ docker compose --env-file .env config --images +mtusi-messenger:lab7 +grafana/tempo:2.6.1 +otel/opentelemetry-collector-contrib:0.111.0 +grafana/tempo:2.6.1 +mtusi-messenger:lab7 +haproxy:3.0.5-alpine +postgres:16.4-alpine +mtusi-messenger:lab7 +openbao/openbao:2.6.4 +redis:8.6.8 +pgsty/minio:RELEASE.2026-08-04T00-00-00Z +haproxy:3.0.5-alpine +redis:8.6.8 +grafana/loki:3.3.2 +prom/prometheus:v2.55.1 +grafana/grafana:11.4.0 +[exit 0] + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe scripts/lab7.py status + Container mtusi-lab7-pki-run-13ee8b8769e7 Creating + Container mtusi-lab7-pki-run-13ee8b8769e7 Created +lb 5e4750312ca6226a75e26ae95c920569649c1ccf until 2027-03-02 active (issued 1) +api 50cce6049ba35e64bb5b2106b5c133c6a799e95c until 2027-03-02 active (issued 1) +worker 71cff8f134eae425db3b3de0e761ca63103113f5 until 2027-03-02 active (issued 1) +migrate 37276283a32d29fd2406987fd55cbce32b43557 until 2027-03-02 active (issued 1) +postgres 14872f2539375f9b88b385d9b5828b34fb698c3a until 2027-03-02 active (issued 1) +redis 57141d778043a0730d5967bebf87ddc09f6df1d0 until 2027-03-02 active (issued 1) +broker 56e54961655e27efc3c5bbf9fa0c83ca76628b until 2027-03-02 active (issued 1) +s3 522ba07b9c4d349ec1cfda09813f10ae999f63c3 until 2027-03-02 active (issued 1) +openbao 4f460ed62fba96cfb4c074266c9cd3a461017e4 until 2027-03-02 active (issued 1) +otel-gw 293dddb23f7adf8e299850aab7083a1995b6b219 until 2027-03-02 active (issued 1) +otel-collector ff0be38903220da32764b2d17747c09472648a8 until 2027-03-02 active (issued 1) +prometheus 493bc67fbda31cacf600ee5921bd4efdab8aefdd until 2027-03-02 active (issued 1) +loki f6cca83aafed85eadeaf489f3ce9f9ce25a1225 until 2027-03-02 active (issued 1) +tempo 5df32da279361c141f39f304c59f5213f208da04 until 2027-03-02 active (issued 1) +grafana 191436396285f645dc555e1767215446deb495ec until 2027-03-02 active (issued 1) +redis-ops 3ac9ff81abb27e41a08f7fb24648a53e3f4b8a72 until 2027-03-02 active (issued 1) +broker-ops 24c5461ebf37f5ae324ebde46b95a635fe5f82bc until 2027-03-02 active (issued 1) +intruder 6c0ac69b9bf575a3f7c5131d216a262bb893f401 until 2027-03-02 active (issued 1) +revoked serials: 0 +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab7-api-1 mtusi-messenger:lab7 "python -m app" api About a minute ago Up About a minute (healthy) 8443/tcp +mtusi-lab7-api-2 mtusi-messenger:lab7 "python -m app" api About a minute ago Up About a minute (healthy) 8443/tcp +mtusi-lab7-broker-1 redis:8.6.8 "docker-entrypoint.s…" broker 3 minutes ago Up 3 minutes (healthy) 6379/tcp +mtusi-lab7-grafana-1 grafana/grafana:11.4.0 "/bin/sh -c 'export …" grafana About a minute ago Up About a minute 127.0.0.1:3000->3000/tcp +mtusi-lab7-lb-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" lb About a minute ago Up About a minute (healthy) 127.0.0.1:8443-8445->8443-8445/tcp +mtusi-lab7-loki-1 grafana/loki:3.3.2 "/usr/bin/loki -conf…" loki About a minute ago Up About a minute 3100/tcp +mtusi-lab7-openbao-1 openbao/openbao:2.6.4 "bao server -config=…" openbao 17 minutes ago Up 15 minutes (healthy) 8200/tcp +mtusi-lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.111.0 "/otelcol-contrib --…" otel-collector About a minute ago Up About a minute +mtusi-lab7-otel-gw-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" otel-gw About a minute ago Up About a minute (healthy) +mtusi-lab7-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 14 minutes ago Up 14 minutes (healthy) 5432/tcp +mtusi-lab7-prometheus-1 prom/prometheus:v2.55.1 "/bin/prometheus --c…" prometheus About a minute ago Up About a minute (healthy) 9090/tcp +mtusi-lab7-redis-1 redis:8.6.8 "docker-entrypoint.s…" redis 3 minutes ago Up 3 minutes (healthy) 6379/tcp +mtusi-lab7-s3-1 pgsty/minio:RELEASE.2026-08-04T00-00-00Z "/usr/bin/docker-ent…" s3 14 minutes ago Up 14 minutes (healthy) 9000/tcp +mtusi-lab7-tempo-1 grafana/tempo:2.6.1 "/tempo -config.file…" tempo About a minute ago Up About a minute +mtusi-lab7-worker-1 mtusi-messenger:lab7 "python -m app.worker" worker About a minute ago Up About a minute (healthy) 8443/tcp +openbao: {'initialized': True, 'sealed': False, 'version': '2.6.4', 'storage_type': 'raft'} + $ docker compose --env-file C:\Users\79152\Desktop\mtusi2026lab7\.env --profile ops run --rm pki list + $ docker compose --env-file C:\Users\79152\Desktop\mtusi2026lab7\.env ps +[exit 0] diff --git a/evidence/student-tests.txt b/evidence/student-tests.txt new file mode 100644 index 00000000..8a9fa23f --- /dev/null +++ b/evidence/student-tests.txt @@ -0,0 +1,67 @@ +# student-tests +# date: 2026-12-03T00:24:49 commit: cbbe525 + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/run.py --base-url https://localhost:8443 +== аутентификация == + ok - wrong password -> 401 + Basic challenge + ok - unknown user -> 401 (same as wrong password) + ok - no token -> 401 + Bearer challenge + ok - X-User-Id alone gives no access + ok - unknown/forged token -> 401 + ok - Basic on business endpoint -> 401 + ok - X-User-Id cannot override bearer identity + ok - password shorter than 12 -> 400 +== logout == + ok - logout -> 204 + ok - token after logout -> 401 + ok - second logout -> 401 +== гонка регистрации одного username == + ok - 20 parallel registrations -> one 201, nineteen 409 (got [201, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409, 409]) +== ошибки и доступ (из lab1) == + ok - malformed JSON -> 400 + ok - duplicate username -> 409 + ok - invalid username 'review123\n' -> 400, not 500 (got 400) + ok - invalid username 'review123\r\n' -> 400, not 500 (got 400) + ok - invalid username ' review123' -> 400, not 500 (got 400) + ok - invalid username 'Review123' -> 400, not 500 (got 400) + ok - invalid username 'ab' -> 400, not 500 (got 400) + ok - blank message -> 400 + ok - sender_id in body is rejected + ok - outsider POST to foreign chat -> 404 + ok - outsider GET foreign history -> 404 + ok - invalid chat uuid -> 400 +== пагинация == + ok - 5 messages / limit 2 -> 3 pages, no duplicates + ok - cursor from another chat -> 400 +== Content-Type == + ok - valid JSON with text/plain -> 415 (got 415) + ok - message with text/plain -> 415 (got 415) + ok - text/plain without token -> 401 first (got 401) + ok - application/json; charset=utf-8 accepted (got 201) + +30 passed, 0 failed +[exit 0] + +$ C:\Users\79152\AppData\Local\Python\pythoncore-3.14-64\python.exe student-tests/idempotency.py --base-url https://localhost:8443 +== 20 параллельных запросов с одним ключом == + ok - all parallel repeats -> 201 (got [201]) + ok - all responses carry the same message id (1 distinct) + ok - requests were served by >=2 replicas (2) + ok - exactly one message in history + ok - every replay returns the identical Message +== семантика ключа == + ok - same key, different body -> 409 (got 409) + ok - other JSON formatting = same request (got 201) + ok - same key in another chat is independent + ok - same key from another user is independent + ok - missing Idempotency-Key -> 400 (got 400) + ok - invalid key 'has space'... -> 400 (got 400) + ok - invalid key 'xxxxxxxxxxxx'... -> 400 (got 400) + ok - invalid key 'slash/key'... -> 400 (got 400) + ok - replay without session -> 401, access re-checked (got 401) +== неопределённый результат: клиент повторяет с тем же ключом == + ok - retry after uncertain result -> 201 + ok - still exactly one message + +16 passed, 0 failed +[exit 0] diff --git a/evidence/telemetry-config.txt b/evidence/telemetry-config.txt new file mode 100644 index 00000000..84c8966f --- /dev/null +++ b/evidence/telemetry-config.txt @@ -0,0 +1,46 @@ +# telemetry-config +# date: 2026-12-03T00:29:19 commit: cbbe525 + +$ docker compose --env-file .env ps otel-gw otel-collector prometheus loki tempo grafana +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi-lab7-grafana-1 grafana/grafana:11.4.0 "/bin/sh -c 'export …" grafana 7 minutes ago Up 7 minutes 127.0.0.1:3000->3000/tcp +mtusi-lab7-loki-1 grafana/loki:3.3.2 "/usr/bin/loki -conf…" loki 8 minutes ago Up 7 minutes 3100/tcp +mtusi-lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.111.0 "/otelcol-contrib --…" otel-collector 8 minutes ago Up 7 minutes +mtusi-lab7-otel-gw-1 haproxy:3.0.5-alpine "docker-entrypoint.s…" otel-gw 8 minutes ago Up 7 minutes (healthy) +mtusi-lab7-prometheus-1 prom/prometheus:v2.55.1 "/bin/prometheus --c…" prometheus 8 minutes ago Up 7 minutes (healthy) 9090/tcp +mtusi-lab7-tempo-1 grafana/tempo:2.6.1 "/tempo -config.file…" tempo 8 minutes ago Up 7 minutes +[exit 0] + +$ docker compose --env-file .env exec -T prometheus promtool check config /etc/prometheus/prometheus.yml +Checking /etc/prometheus/prometheus.yml + SUCCESS: 1 rule files found + SUCCESS: /etc/prometheus/prometheus.yml is valid prometheus config file syntax + +Checking /etc/prometheus/rules/messenger.yml + SUCCESS: 15 rules found + +[exit 0] + +$ docker compose --env-file .env exec -T prometheus promtool check rules /etc/prometheus/rules/messenger.yml +Checking /etc/prometheus/rules/messenger.yml + SUCCESS: 15 rules found + +[exit 0] + +$ docker compose --env-file .env logs --tail 15 otel-collector +otel-collector-1 | 2026-12-02T23:21:22.804Z warn service@v0.111.0/service.go:191 service::telemetry::metrics::address is being deprecated in favor of service::telemetry::metrics::readers +otel-collector-1 | 2026-12-02T23:21:22.804Z info telemetry/metrics.go:70 Serving metrics {"address": "127.0.0.1:8888", "metrics level": "Detailed"} +otel-collector-1 | 2026-12-02T23:21:22.805Z info memorylimiter/memorylimiter.go:75 Memory limiter configured {"kind": "processor", "name": "memory_limiter", "pipeline": "traces", "limit_mib": 160, "spike_limit_mib": 40, "check_interval": 1} +otel-collector-1 | 2026-12-02T23:21:22.805Z warn prometheusremotewriteexporter@v0.111.0/factory.go:47 Currently, remote_write_queue.num_consumers doesn't have any effect due to incompatibility with Prometheus remote write API. The value will be ignored. Please see https://github.com/open-telemetry/opentelemetry-collector/issues/2949 for more information. {"kind": "exporter", "data_type": "metrics", "name": "prometheusremotewrite"} +otel-collector-1 | 2026-12-02T23:21:22.806Z info service@v0.111.0/service.go:208 Starting otelcol-contrib... {"Version": "0.111.0", "NumCPU": 6} +otel-collector-1 | 2026-12-02T23:21:22.806Z info extensions/extensions.go:39 Starting extensions... +otel-collector-1 | 2026-12-02T23:21:22.807Z info extensions/extensions.go:42 Extension is starting... {"kind": "extension", "name": "health_check"} +otel-collector-1 | 2026-12-02T23:21:22.807Z info healthcheckextension@v0.111.0/healthcheckextension.go:33 Starting health_check extension {"kind": "extension", "name": "health_check", "config": {"Endpoint":"127.0.0.1:13133","TLSSetting":null,"CORS":null,"Auth":null,"MaxRequestBodySize":0,"IncludeMetadata":false,"ResponseHeaders":null,"CompressionAlgorithms":null,"ReadTimeout":0,"ReadHeaderTimeout":0,"WriteTimeout":0,"IdleTimeout":0,"Path":"/","ResponseBody":null,"CheckCollectorPipeline":{"Enabled":false,"Interval":"5m","ExporterFailureThreshold":5}}} +otel-collector-1 | 2026-12-02T23:21:22.807Z info extensions/extensions.go:59 Extension started. {"kind": "extension", "name": "health_check"} +otel-collector-1 | 2026-12-02T23:21:22.809Z info otlpreceiver@v0.111.0/otlp.go:169 Starting HTTP server {"kind": "receiver", "name": "otlp", "data_type": "traces", "endpoint": "127.0.0.1:14318"} +otel-collector-1 | 2026-12-02T23:21:22.811Z info prometheusreceiver@v0.111.0/metrics_receiver.go:118 Starting discovery manager {"kind": "receiver", "name": "prometheus/self", "data_type": "metrics"} +otel-collector-1 | 2026-12-02T23:21:22.812Z info targetallocator/manager.go:179 Scrape job added {"kind": "receiver", "name": "prometheus/self", "data_type": "metrics", "jobName": "otel-collector"} +otel-collector-1 | 2026-12-02T23:21:22.814Z info healthcheck/handler.go:132 Health Check state change {"kind": "extension", "name": "health_check", "status": "ready"} +otel-collector-1 | 2026-12-02T23:21:22.814Z info service@v0.111.0/service.go:234 Everything is ready. Begin running and processing data. +otel-collector-1 | 2026-12-02T23:21:22.814Z info prometheusreceiver@v0.111.0/metrics_receiver.go:187 Starting scrape manager {"kind": "receiver", "name": "prometheus/self", "data_type": "metrics"} +[exit 0] diff --git a/evidence/tls-audit.txt b/evidence/tls-audit.txt new file mode 100644 index 00000000..8ef67d38 --- /dev/null +++ b/evidence/tls-audit.txt @@ -0,0 +1,139 @@ +# tls-audit +# date: 2026-12-03T00:23:16 commit: cbbe525 + +$ docker compose --env-file .env --profile ops run --rm sectest student-tests/tls_audit.py + Container mtusi-lab7-sectest-run-66b95663f541 Creating + Container mtusi-lab7-sectest-run-66b95663f541 Created + +== LB → API (каждая реплика): mTLS + allowlist identity lb + CRL + ok lb→api реплик за именем api -> 2 + ok lb→api 172.25.0.2 identity lb (разрешена) -> 200 + ok lb→api 172.25.0.2 без сертификата -> closed by server + ok lb→api 172.25.0.2 чужой CA (CN=lb!) -> closed by server + ok lb→api 172.25.0.2 тот же CA, identity intruder -> closed by server + ok lb→api 172.25.0.2 тот же CA, identity worker -> closed by server + ok lb→api 172.25.0.2 тот же CA, identity grafana -> closed by server + ok lb→api 172.25.0.2 клиент: неверное имя сервера -> server cert rejected: Hostname mismatch, certificate is not valid for 'postgres'. + ok lb→api 172.25.0.3 identity lb (разрешена) -> 200 + ok lb→api 172.25.0.3 без сертификата -> closed by server + ok lb→api 172.25.0.3 чужой CA (CN=lb!) -> closed by server + ok lb→api 172.25.0.3 тот же CA, identity intruder -> closed by server + ok lb→api 172.25.0.3 тот же CA, identity worker -> closed by server + ok lb→api 172.25.0.3 тот же CA, identity grafana -> closed by server + ok lb→api 172.25.0.3 клиент: неверное имя сервера -> server cert rejected: Hostname mismatch, certificate is not valid for 'postgres'. + ok lb→api plaintext HTTP на порт API -> no plaintext answer + +== API/worker → broker: mTLS, CN сертификата = ACL-пользователь (producer / consumer) + ok api/worker→broker api: XLEN потока (диагностика) -> OK:0 + ok api/worker→broker api: XREADGROUP (consumer) — запрещено -> NOPERM User api has no permissions to run the 'xreadgroup' command + ok api/worker→broker api: XACK — запрещено -> NOPERM User api has no permissions to run the 'xack' command + ok api/worker→broker api: FLUSHALL — запрещено -> NOPERM User api has no permissions to run the 'flushall' command + ok api/worker→broker api: CONFIG — запрещено -> NOPERM User api has no permissions to run the 'config|get' command + ok api/worker→broker worker: XINFO GROUPS -> OK:[{b'name': b'workers', b'consu + ok api/worker→broker worker: ключи сессий — запрещено -> NOPERM No permissions to access a key + ok api/worker→broker worker: CONFIG SET — запрещено -> NOPERM User worker has no permissions to run the 'config|set' command + ok api/worker→broker тот же CA, CN intruder — нет ACL-пользователя -> NOAUTH HELLO must be called with the client already authenticated, otherw + ok api/worker→broker тот же CA, CN grafana -> NOAUTH HELLO must be called with the client already authenticated, otherw + ok api/worker→broker чужой CA -> conn refused: Error while reading from broker:6379 : (1, '[SSL: + ok api/worker→broker без сертификата -> conn refused: Error while reading from broker:6379 : (1, '[SSL: + ok api/worker→broker ACL DRYRUN api XADD -> OK + ok api/worker→broker ACL DRYRUN worker XREADGROUP -> OK + ok api/worker→broker ACL DRYRUN worker XADD -> OK + +== API → redis (кэш сессий, общий rate limit): mTLS, ACL api — только sess:*, rl:* + ok api→redis api: GET sess:* -> OK:None + ok api→redis api: INCR rl:* (rate limit) -> OK + ok api→redis api: KEYS * — запрещено -> NOPERM User api has no permissions to run the 'keys' command + ok api→redis api: чужой префикс ключей -> NOPERM No permissions to access a key + ok api→redis worker: в кэш доступа нет -> NOAUTH HELLO must be called with the client already authenticated, otherw + ok api→redis тот же CA, CN intruder -> NOAUTH HELLO must be called with the client already authenticated, otherw + ok api→redis без сертификата -> conn refused: Error while reading from redis:6379 : (1, '[SSL: T + +== API/worker → OpenBao: TLS + cert auth (CN = роль) + политика роли + TTL + ok app→openbao cert login api сертификатом api -> 200 ttl=900s policies=default,messenger-api + ok app→openbao cert login worker сертификатом worker -> 200 ttl=900s policies=default,messenger-worker + ok app→openbao роль api сертификатом worker -> 400 + ok app→openbao роль api, тот же CA, CN intruder -> 400 + ok app→openbao чужой CA (CN=lb) -> 400 + ok app→openbao без сертификата -> 400 + ok app→openbao роль worker сертификатом api -> 400 + ok app→openbao api читает свой путь -> 200 + ok app→openbao api: чужой путь worker -> 403 + ok app→openbao api: путь migrate (владелец БД) -> 403 + ok app→openbao api: запись в свой путь -> 403 + ok app→openbao api: metadata/версии -> 403 + ok app→openbao api: изменить свою политику -> 403 + ok app→openbao api: список политик -> 403 + ok app→openbao api: выпустить токен -> 403 + ok app→openbao worker: путь api (ключи S3/пароль БД api) -> 403 + ok app→openbao renew-self токена api -> 200 ttl=900 + ok app→openbao после revoke-self токен не работает -> 403 + ok app→openbao plaintext HTTP -> no plaintext answer + +== API/worker → PostgreSQL: TLS verify-full + клиентский сертификат (CN = роль) + SCRAM + ok app→postgres api: сертификат api + пароль api -> OK:api + ok app→postgres worker: сертификат worker + пароль -> OK:worker + ok app→postgres роль api, сертификат worker -> password authentication failed for user "api" + ok app→postgres роль api, тот же CA, CN intruder -> password authentication failed for user "api" + ok app→postgres роль api без сертификата -> connection requires a valid client certificate + ok app→postgres без TLS (sslmode=disable) -> pg_hba.conf rejects connection for host "172.21.0.9", user "api", database "messenger", no + ok app→postgres сертификат api, неверный пароль -> password authentication failed for user "api" + ok app→postgres суперпользователь postgres по сети -> pg_hba.conf rejects connection for host "172.21.0.9", user "postgres", database "messenger + ok app→postgres verify-full: подключение по IP (нет в SAN) -> server certificate for "postgres" (and 2 other names) does not match host name "172.21.0.5 + ok app→postgres worker: SELECT users -> permission denied for table users + ok app→postgres worker: SELECT messages -> permission denied for table messages + ok app→postgres worker: SELECT sessions -> permission denied for table sessions + ok app→postgres api: DROP TABLE -> must be owner of table messages + ok app→postgres api: UPDATE attachments.status -> permission denied for table attachments + ok app→postgres api: CREATE TABLE -> permission denied for schema public + ok app→postgres api: DELETE users -> permission denied for table users + ok app→postgres api: SELECT users (нужно для входа) -> OK:6 + +== API/worker → MinIO: HTTPS + отдельный пользователь роли + prefix-политика + ok app→s3 api: PUT staging/ -> ALLOWED + ok app→s3 api: PUT originals/ -> AccessDenied + ok app→s3 api: GET staging/ -> AccessDenied + ok app→s3 worker: GET staging/ -> ALLOWED + ok app→s3 worker: PUT staging/ (только API принимает файлы) -> AccessDenied + ok app→s3 worker: PutBucketPolicy -> AccessDenied + ok app→s3 worker: DELETE staging/ (после обработки) -> ALLOWED + ok app→s3 plaintext HTTP -> no plaintext answer + +== API/worker → Collector (otel-gw): mTLS + allowlist CN {api, worker} + CRL + ok app→collector OTLP как api -> 200 + ok app→collector OTLP как worker -> 200 + ok app→collector OTLP как grafana -> closed by gateway + ok app→collector OTLP как intruder -> closed by gateway + ok app→collector OTLP как rogue -> tls alert: TLSV1_ALERT_UNKNOWN_CA + ok app→collector OTLP как none -> tls alert: TLSV13_ALERT_CERTIFICATE_REQUIRED + ok app→collector приёмник Collector 14318 из сети -> ConnectionRefusedError + ok app→collector метрики Collector 8888 из сети -> ConnectionRefusedError + ok app→collector health Collector 13133 из сети -> ConnectionRefusedError + +== Collector/Grafana → Prometheus/Loki/Tempo: mTLS; Prometheus — ещё и allowlist SAN + ok →prometheus как grafana -> 200 + ok →prometheus как otel-collector -> 200 + ok →prometheus как none -> tls alert: TLSV13_ALERT_CERTIFICATE_REQUIRED + ok →prometheus как rogue -> tls alert: TLSV1_ALERT_UNKNOWN_CA + ok →prometheus тот же CA, CN intruder -> tls alert: SSLV3_ALERT_BAD_CERTIFICATE + ok →loki как grafana -> 200 + ok →loki как otel-collector -> 200 + ok →loki как none -> tls alert: TLSV13_ALERT_CERTIFICATE_REQUIRED + ok →loki как rogue -> tls alert: TLSV1_ALERT_UNKNOWN_CA + ok →loki тот же CA, CN intruder -> 200 + ok →tempo как grafana -> 200 + ok →tempo как otel-collector -> 200 + ok →tempo как none -> tls alert: TLSV13_ALERT_CERTIFICATE_REQUIRED + ok →tempo как rogue -> tls alert: TLSV1_ALERT_UNKNOWN_CA + ok →tempo тот же CA, CN intruder -> 200 + +== Оператор → Grafana: HTTPS, вход только с паролем + ok operator→grafana API без логина -> 401 + ok operator→grafana HTTPS, сертификат сервера по CA -> 200 + +== Клиент → LB: только TLS ≥ 1.2, сертификат по CA и имени + ok client→lb TLS 1.0/1.1 -> SSLError + ok client→lb TLS 1.2+ по CA, SNI localhost -> 200 + +связей проверено: 12; проверок: 110; 110 passed, 0 failed +[exit 0] diff --git a/evidence/worker-limits.txt b/evidence/worker-limits.txt new file mode 100644 index 00000000..c100f367 --- /dev/null +++ b/evidence/worker-limits.txt @@ -0,0 +1,12 @@ +# worker-limits +# date: 2026-12-03T00:25:04 commit: cbbe525 + +$ docker compose --env-file .env exec -T worker python -m app.tools limits-selftest + ok normal 320x200 with alpha: ok (3.9s) + ok pixel limit (36 Mp > limit 10 Mp): invalid_image: pixel limit (2.7s) + ok memory limit (36 Mp, RLIMIT_AS 120 MiB): invalid_image: memory limit (3.0s) + ok corrupt/truncated PNG: invalid_image: cannot decode: OSError (2.3s) + ok time limit (hangs 10 s, timeout 2 s): timeout(killed) (2.0s) + +5 passed, 0 failed +[exit 0] diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg index 78491421..4a1b4b88 100644 --- a/infra/haproxy/haproxy.cfg +++ b/infra/haproxy/haproxy.cfg @@ -31,6 +31,8 @@ defaults timeout client 30s timeout server 30s timeout http-request 10s + # Health-check реплики (mTLS-handshake + SELECT 1): при CPU, занятом Argon2id, 0,5 c мало. + timeout check 1500ms # Повтор только при ошибке УСТАНОВКИ соединения (запрос ещё не отправлен) — # безопасно даже для POST; redispatch отправляет повтор на другую реплику. retries 3 diff --git a/infra/openbao/openbao.hcl b/infra/openbao/openbao.hcl index a58a1afb..8b4a29fb 100644 --- a/infra/openbao/openbao.hcl +++ b/infra/openbao/openbao.hcl @@ -24,4 +24,12 @@ listener "tcp" { } # Аудит: каждый запрос (значения секретов — в виде HMAC) пишется в файл на volume. -# Включается оператором после init: bao audit enable file file_path=/openbao/logs/audit.log +# С OpenBao 2.3.2 включение аудита через API запрещено (CVE-2025-54997) — устройство +# объявляется декларативно в конфиге и создаётся на активном узле при старте/SIGHUP. +audit "file" "file" { + description = "messenger lab7: audit log on volume baologs" + options { + file_path = "/openbao/logs/audit.log" + mode = "0600" + } +} diff --git a/infra/redis/README.md b/infra/redis/README.md new file mode 100644 index 00000000..84a3db0b --- /dev/null +++ b/infra/redis/README.md @@ -0,0 +1,17 @@ +# Redis-кэш и брокер (lab7) + +Оба — Redis 8.6.8, только TLS (`port 0`, `tls-port 6379`), `tls-auth-clients yes`, +`tls-auth-clients-user CN`: ACL-пользователь = CN клиентского сертификата. Паролей нет — +владение ключом сертификата роли и есть credential. `default` выключен: сертификат того же CA +с неизвестным CN (grafana, intruder) прав не получает (NOAUTH). + +ACL-файлы Redis не допускают комментариев, поэтому пояснения здесь. + +`cache.acl` (кэш сессий и счётчики rate limit): +- `api` — только ключи `sess:*` и `rl:*`, команды GET/SET/DEL/EXPIRE/TTL/INCR(BY)/MULTI/EXEC. +- `redis-ops` — оператор (healthcheck, `docker compose exec redis sh /usr/local/bin/rcli`). + +`broker.acl` (Redis Streams заданий): +- `api` — только producer: `XADD` в `attachments:jobs`, длина/группы для диагностики; DLQ — только чтение (`%R~`). +- `worker` — consumer: группа, чтение, `XACK`, `XAUTOCLAIM`, DLQ, relay (`XADD`), флаги `fault:*`. +- `broker-ops` — оператор, полные права, только изнутри контейнера брокера. diff --git a/infra/redis/broker.acl b/infra/redis/broker.acl index d3e7cf89..c731edb5 100644 --- a/infra/redis/broker.acl +++ b/infra/redis/broker.acl @@ -1,10 +1,4 @@ -# ACL брокера (Redis 8.6+, tls-auth-clients-user CN): ACL-пользователь = CN клиентского сертификата. -# Пароли не используются: владение ключом сертификата роли и есть credential. -# default выключен: сертификат от того же CA с неизвестным CN (grafana, intruder) прав не получает. user default off -# api — только producer: XADD в поток заданий; чтение длины/групп для диагностики. DLQ — только чтение. user api on resetchannels ~attachments:jobs %R~attachments:jobs:dlq -@all +xadd +xlen +xinfo|groups +exists +ping +client|setinfo -# worker — consumer: группа, чтение, подтверждение, перехват брошенных, DLQ, relay (XADD), флаги fault:*. user worker on resetchannels ~attachments:jobs ~attachments:jobs:dlq ~fault:* -@all +xreadgroup +xautoclaim +xack +xdel +xadd +xgroup|create +xlen +xinfo|groups +xrevrange +exists +get +getdel +decr +decrby +del +ping +client|setinfo -# Оператор (только из контейнера брокера: healthcheck, docker compose exec): полные права. user broker-ops on ~* &* +@all diff --git a/infra/redis/cache.acl b/infra/redis/cache.acl index a7289419..c3f567ef 100644 --- a/infra/redis/cache.acl +++ b/infra/redis/cache.acl @@ -1,5 +1,3 @@ -# ACL кэша сессий и счётчиков rate limit (Redis 8.6+, пользователь = CN сертификата). user default off -# api — только ключи сессий (sess:*) и лимитов (rl:*), только нужные команды. user api on resetchannels ~sess:* ~rl:* -@all +get +set +del +expire +ttl +incr +incrby +multi +exec +discard +ping +client|setinfo user redis-ops on ~* &* +@all diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml index 9569a9d2..fae9510d 100644 --- a/infra/tempo/tempo.yaml +++ b/infra/tempo/tempo.yaml @@ -1,6 +1,8 @@ # Tempo 2.6.1, single binary: хранит трассы на volume /var/tempo (локальный backend). # lab7: приём OTLP gRPC и HTTP-API запросов (Grafana) — только mTLS нашего CA; # внутренний gRPC (querier ↔ frontend) — только 127.0.0.1. Сеть tstore: otel-collector и grafana. +# Стриминг результатов поиска в Grafana (gRPC поверх HTTP-порта) — рекомендация Grafana 10.1+. +stream_over_http_enabled: true server: http_listen_port: 3200 grpc_listen_address: 127.0.0.1 diff --git a/requirements.txt b/requirements.txt index 1098d562..78d7f2a4 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,7 +9,7 @@ redis==8.1.0 # lab4: S3-клиент (MinIO) и проверка изображений boto3==1.38.0 botocore==1.38.0 -pillow==11.2.1 +pillow==13.0.0 # lab6: OpenTelemetry SDK + экспорт OTLP/HTTP + автоинструментация opentelemetry-api==1.45.2 opentelemetry-sdk==1.45.2 @@ -21,4 +21,4 @@ opentelemetry-instrumentation-system-metrics==0.66b2 opentelemetry-instrumentation-logging==0.66b2 psutil==7.2.2 # lab7: CRL/сертификаты (проверка отзыва в API, операторский УЦ infra/pki) -cryptography==46.0.3 +cryptography==50.0.2 diff --git a/scripts/lab7.py b/scripts/lab7.py index d8f35919..d4b375bb 100644 --- a/scripts/lab7.py +++ b/scripts/lab7.py @@ -43,8 +43,13 @@ def run(args: list[str], *, input: str | None = None, env: dict | None = None, c capture: bool = True, quiet: bool = False) -> subprocess.CompletedProcess: if not quiet: print(" $", " ".join(a if len(a) < 120 else a[:117] + "..." for a in args)) - p = subprocess.run(args, cwd=ROOT, input=input, text=True, encoding="utf-8", errors="replace", + # stdin передаём байтами: в текстовом режиме Windows превращает \n в \r\n, и sh в контейнере + # получает «set -eu\r» (invalid option). Вывод декодируем сами. + p = subprocess.run(args, cwd=ROOT, input=input.encode("utf-8") if input is not None else None, capture_output=capture, env={**os.environ, **(env or {})}) + if capture: + p.stdout = (p.stdout or b"").decode("utf-8", "replace") + p.stderr = (p.stderr or b"").decode("utf-8", "replace") if check and p.returncode != 0: # stderr команд не содержит секретов (секреты идут только через stdin/env) sys.exit(f"command failed ({p.returncode}): {' '.join(args[:6])}\n{(p.stderr or '')[-800:]}") @@ -174,8 +179,8 @@ def configure_openbao(token: str) -> dict: if "cert/" not in auths: bao(["auth", "enable", "cert"], token=token) audits = json.loads(bao(["audit", "list", "-format=json"], token=token, check=False, quiet=True).stdout or "{}") - if "file/" not in audits: - bao(["audit", "enable", "file", "file_path=/openbao/logs/audit.log"], token=token) + # аудит объявлен в infra/openbao/openbao.hcl (API-включение в 2.6 запрещено) — только проверяем + print(" audit devices:", ", ".join(sorted(audits)) or "NONE (check openbao.hcl)") for name in ("messenger-api", "messenger-worker", "messenger-migrate", "operator"): bao(["policy", "write", name, f"/openbao/policies/{name}.hcl"], token=token) for r in ROLES: diff --git a/student-tests/common.py b/student-tests/common.py index beb69a24..e0e89894 100644 --- a/student-tests/common.py +++ b/student-tests/common.py @@ -172,20 +172,38 @@ def raw_http(base: str, method: str, path: str, headers: dict, chunks=(), chunke раньше (413 до конца тела) — тогда прекращаем отправку и читаем ответ. Возвращает (status | None, body_bytes).""" u = urlparse(base) - sock = socket.create_connection((u.hostname, u.port or 80), timeout=timeout) + port = u.port or (443 if u.scheme == "https" else 80) + sock = socket.create_connection((u.hostname, port), timeout=timeout) + if u.scheme == "https": # lab7: тот же TLS с проверкой CA и имени, что у urllib + sock = tls_context().wrap_socket(sock, server_hostname=u.hostname) try: - lines = [f"{method} {path} HTTP/1.1", f"Host: {u.hostname}:{u.port or 80}", "Connection: close"] + lines = [f"{method} {path} HTTP/1.1", f"Host: {u.hostname}:{port}", "Connection: close"] lines += [f"{k}: {v}" for k, v in headers.items()] if chunked: lines.append("Transfer-Encoding: chunked") sock.sendall(("\r\n".join(lines) + "\r\n\r\n").encode("latin-1")) + early = b"" for part in chunks: ready, _, _ = select.select([sock], [], [], 0) if ready: - break # сервер уже ответил — дальше не шлём + # По TLS 1.3 сокет «читаем» и без ответа: сервер шлёт после handshake служебные + # записи (NewSessionTicket). Пробуем прочитать неблокирующе: нет данных приложения — + # шлём дальше; есть ответ или закрытие — прекращаем отправку. + sock.setblocking(False) + try: + early = sock.recv(65536) + got_reply = True + except (ssl.SSLWantReadError, BlockingIOError): + got_reply = False + except OSError: + got_reply = True + finally: + sock.settimeout(timeout) + if got_reply: + break # сервер уже ответил — дальше не шлём try: sock.sendall(f"{len(part):x}\r\n".encode() + part + b"\r\n" if chunked else part) - except (BrokenPipeError, ConnectionResetError): + except OSError: # сервер закрыл приём (в т.ч. ssl.SSLError, WinError 10053) break else: if chunked and not close_after_send: @@ -195,14 +213,14 @@ def raw_http(base: str, method: str, path: str, headers: dict, chunks=(), chunke pass if close_after_send: return None, b"" # обрыв загрузки: ответ не ждём - data = b"" + data = early try: while True: piece = sock.recv(65536) if not piece: break data += piece - except (ConnectionResetError, socket.timeout): + except OSError: # ConnectionReset, timeout, TLS EOF без close_notify pass finally: sock.close() diff --git a/student-tests/observability.py b/student-tests/observability.py index f8cd5e13..359edf5f 100644 --- a/student-tests/observability.py +++ b/student-tests/observability.py @@ -217,8 +217,16 @@ def main(): if not tel.direct: for uid in ("prom", "loki", "tempo"): st, h = tel.get(f"{tel.grafana}/api/datasources/uid/{uid}/health") - rep.check(st == 200 and isinstance(h, dict) and h.get("status") == "OK", - f"Grafana datasource {uid}: {h.get('message', h) if isinstance(h, dict) else h}") + msg = h.get("message", h) if isinstance(h, dict) else h + if uid == "tempo" and msg == "Method not implemented": + # Health API у плагина Tempo в Grafana 11 не реализован — проверяем сам путь + # Grafana → Tempo (mTLS сертификатом grafana) запросом через datasource proxy. + st, d = tel.get(f"{tel.grafana}/api/datasources/proxy/uid/tempo/api/search", {"limit": 1}) + rep.check(st == 200 and isinstance(d, dict) and "traces" in d, + f"Grafana datasource tempo: health API не реализован плагином; " + f"поиск через datasource (mTLS) → {st}, трасс: {len(d.get('traces', [])) if isinstance(d, dict) else d}") + continue + rep.check(st == 200 and isinstance(h, dict) and h.get("status") == "OK", f"Grafana datasource {uid}: {msg}") st, dash = tel.get(f"{tel.grafana}/api/dashboards/uid/messenger-lab6") panels = [p for p in dash.get("dashboard", {}).get("panels", []) if p.get("type") != "row"] if st == 200 else [] rep.check(st == 200 and len(panels) >= 15, diff --git a/student-tests/security_neg.py b/student-tests/security_neg.py index c5376977..290f1a1c 100644 --- a/student-tests/security_neg.py +++ b/student-tests/security_neg.py @@ -252,12 +252,15 @@ def section_docker(rep: Report) -> None: roots = sorted(r["svc"] for r in rows if r["user"] in ("root", "0", "0:0")) print(f" root (без capabilities, ФС read-only): {', '.join(roots) or 'нет'}") img = json.loads(sh(["docker", "image", "inspect", "mtusi-messenger:lab7"]))[0] - env = " ".join(img["Config"].get("Env") or []) - rep.check(not re.search(r"PASSWORD|SECRET|TOKEN|KEY=", env, re.I), "в ENV образа нет паролей/ключей/токенов") + # GPG_KEY — отпечаток публичного ключа подписи релизов Python из базового образа, не секрет + names = [e.split("=", 1)[0] for e in img["Config"].get("Env") or []] + bad = [n for n in names if re.search(r"PASSWORD|SECRET|TOKEN|KEY", n, re.I) and n != "GPG_KEY"] + rep.check(not bad, f"в ENV образа нет паролей/ключей/токенов (переменные: {', '.join(names)}; подозрительные: {bad or 'нет'})") files = sh(["docker", "run", "--rm", "--network", "none", "--entrypoint", "sh", "mtusi-messenger:lab7", "-c", "find / -xdev \\( -name '*.key' -o -name '*.pem' -o -name '.env' -o -name 'tls.crt' \\) " - "-not -path '/usr/*' -not -path '/proc/*' 2>/dev/null | head -5"], check=False).strip() - rep.check(files == "", f"в образе нет ключей/сертификатов/.env {files[:80]}") + "-not -path '/usr/*' -not -path '/proc/*' -not -path '/etc/ssl/certs/*' 2>/dev/null | head -5"], check=False).strip() + rep.check(files == "", f"в образе нет ключей/сертификатов/.env (публичные корневые CA /etc/ssl/certs не в счёт) " + f"{files[:80]}") probe = ("import socket,sys\nfor h,p in (('loki',3100),('prometheus',9090),('tempo',3200),('grafana',3000)," "('openbao',8200),('postgres',5432)):\n try:\n socket.create_connection((h,p),timeout=2).close();print(h,'reachable')\n" " except Exception as e:print(h,type(e).__name__)")