diff --git a/.github/workflows/solution.yml b/.github/workflows/solution.yml new file mode 100644 index 0000000..1609332 --- /dev/null +++ b/.github/workflows/solution.yml @@ -0,0 +1,22 @@ +name: implemented-secure-messenger +on: [push, pull_request] +permissions: + contents: read +jobs: + integration: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - run: python3 -m pip install -r requirements-dev.txt + - run: make check validate + - run: make up + - run: make test test-security + - run: python3 student-tests/security.py + - run: make test-race + - run: make test-persistence ACTION_SCRIPT=scripts/restart.sh + - run: make test-failover ACTION_SCRIPT=scripts/stop-one.sh + - if: always() + run: docker compose down -v --remove-orphans diff --git a/.gitignore b/.gitignore index b5a7189..6fa6175 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,6 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. +# Locally generated CA certificate and operator/test state +certs/ca.crt +infra/tls/revoked.json diff --git a/DEFENSE.md b/DEFENSE.md new file mode 100644 index 0000000..0652213 --- /dev/null +++ b/DEFENSE.md @@ -0,0 +1,143 @@ +# ЛР7: понятный разбор для защиты + +## Что я делал — ответ на первый вопрос + +«Я взял свой работающий мессенджер из шестой лабы и защитил соединения и доступы между его частями. Пользователь обращается по HTTPS. Балансировщик и каждая копия API проверяют сертификаты друг друга; API принимает только сертификат роли балансировщика. База, файловое хранилище, очередь и система наблюдения тоже доступны по защищённым соединениям. + +Я разделил права сервисов. Обработчик фотографий не может читать пароли, пользовательские сессии и сообщения или менять владельца файла. Нужные пароли сервисы получают из OpenBao — отдельного хранилища секретов — по своему сертификату и ограниченной политике. Ключи оператора в приложение не передаются. + +Для исследования я смоделировал утечку доступа обработчика: проверил разрешённые и запрещённые действия, остановил старый процесс, отозвал его доступ, заменил пароль БД и сертификат. Затем запустил чистый обработчик из того же образа и проверил завершение уже принятых задач и совпадение исходных файлов». + +## Схема системы + +```mermaid +flowchart LR + U[Пользователь] -->|HTTPS| L[HAProxy: балансировщик] + L -->|mTLS, только роль LB| A[Две API] + A -->|TLS + отдельная роль| P[(PostgreSQL)] + A -->|mTLS + права на файлы| S[(S3 / MinIO)] + P --> D[Отправитель заданий] + D -->|mTLS + право добавить| B[(Очередь Valkey)] + B -->|mTLS + право обработать| W[Обработчик фотографий] + W --> S + W --> P + A -->|Свой сертификат, своя политика| O[OpenBao] + W --> O + A -->|mTLS| C[Сборщик наблюдений] + W -->|mTLS| C + C --> T[Prometheus / Loki / Tempo] + T --> G[Grafana] +``` + +Для части программ TLS выполняет небольшой шлюз рядом с ними. Шлюз и программа используют одно сетевое пространство, а незашифрованный участок ограничен127.0.0.1 внутри этой границы. Из соседнего контейнера этот локальный порт недоступен. Это проверяется соединением из другого контейнера, а не только чтением конфигурации. + +## Термины без лишней сложности + +| Термин | Что означает здесь | +|---|---| +| TLS / HTTPS | Защищённое соединение. Клиент проверяет сертификат сервера и имя адресата, данные шифруются | +| mTLS | Обе стороны предъявляют сертификаты: сервер также проверяет клиента | +| CA, центр сертификации | Доверенный издатель сертификатов; его закрытый ключ находится у оператора | +| SAN | Поле сертификата с разрешёнными именами. Проверяем точное имя нужного сервиса | +| EKU | Разрешённое применение ключа: клиентское или серверное. Ключ worker не получает право представлять HTTPS ingress | +| Identity | Кем представляется соединяющийся сервис, например worker.client.lab | +| Политика / ACL | Список разрешённых действий. Узнать, кто подключился, недостаточно — нужно разрешить действие | +| Credential / secret | Пароль, ключ или другое подтверждение доступа, которое нельзя публиковать | +| Leaf certificate | Обычный сертификат конкретного сервиса, подписанный CA | +| TTL | Срок действия. Например, сервисный токен OpenBao имеет срок60 секунд | +| Rotation / ротация | Замена пароля или сертификата на новый с прекращением использования старого | +| Revoke / отзыв | Запрет ранее выданного доступа | +| OpenBao | Сервис, который хранит секреты и выдаёт их после проверки identity и политики | +| Sealed / закрытый Bao | OpenBao не открыл своё зашифрованное хранилище и не выдаёт секреты | +| Unseal / открытие Bao | Действие оператора с частями ключа, позволяющее Bao работать с хранилищем | +| tmpfs | Временные файлы в памяти контейнера; туда попадают рабочие секреты | +| Argon2id | Функция для хранения паролей, специально требующая времени и памяти при проверке | +| Rehash | Пересчёт сохранённого хеша с более сильными параметрами после успешного входа | + +## Четыре вопроса из README с ответами + +**1. Какая часть mTLS проверяет шифрование, какая идентичность и где разрешение на действие?** + +При установлении TLS стороны договариваются о ключах, затем данные защищаются шифрованием и контролем целостности. Проверка сертификата устанавливает identity: кто подключился, доверяем ли издателю, не истёк ли срок и соответствует ли имя ожидаемому. В mTLS сертификат проверяет и сервер, и клиент. + +Разрешение действия задаётся отдельно. API разрешает роль LB; очередь дополнительно проверяет свои имя пользователя/пароль и команды; PostgreSQL — права SQL-роли; S3 — права пользователя на нужную область файлов; OpenBao — политику своего пути. Пользователь всё равно должен предъявить Bearer-сессию и состоять в чате. mTLS между сервисами не делает пользователя участником любого чата. + +**2. Почему доверенный CA ещё не означает, что любой его клиент может быть LB?** + +CA подписывает сертификаты разных ролей: обработчика, сборщика наблюдений, балансировщика. Подпись доказывает, что сертификат выдал наш центр, но роль может быть неподходящей. Поэтому API проверяет точный DNS SANlb.client.lab. Сертификат worker или outsider от того же CA отклоняется. + +Сертификаты также ограничены по назначению. Worker получает клиентский ключ без серверного назначения и без имён localhost/LB. Иначе чрезмерно широкий сертификат мог бы дать ему ненужную возможность представляться сервером. Отрицательные проверки выполняются для каждой API-копии, брокера и Collector. + +**3. Где хранится первый секрет для доступа к OpenBao и кто имеет право unseal?** + +Первоначальное доверие создаёт оператор: выпускает короткоживущий сертификат сервиса и передаёт ему только его закрытый ключ и публичный CA. Приложение доказывает владение своим ключом при аутентификации в Bao и получает ограниченный токен. В образе нет общего вечного токена «для получения всех секретов». + +Ключ CA, root token и части ключа для открытия Bao находятся в закрытом каталоге оператора на host. Они не монтируются в API/worker и в сам Bao. Для открытия нужны2 части из3. В учебном стенде всеми частями владеет один оператор; независимые держатели/HSM не реализованы. После рестарта Bao оператор явно выполняет make unseal. Приложение самостоятельно открыть Bao не может. + +**4. Что происходит при истечении credentials, остановке OpenBao и рестарте API?** + +Истёкший сертификат отклоняется при проверке TLS. Истёкшая/отозванная пользовательская сессия даёт401. Сервис повторяет вход в Bao и чтение секретов каждые5 секунд. После последнего успешного чтения он допускает использование конфигурации не дольше60 секунд, затем останавливает рабочий процесс. Проверка TLS не отключается. + +Если API перезапустить при закрытом Bao, он не сможет заново получить секреты и не начнёт обслуживать бизнес-запросы. Уже работавшая другая API может работать до окончания ограниченного срока. После открытия Bao сервисы снова получают конфигурацию; прежние пользовательские сессии и данные остаются в PG/S3. + +Важно различать токен Bao и выданный пароль БД: истечение токена само по себе не меняет статический пароль. Мы отдельно заменяем пароль SQL-роли и завершаем её старые соединения. В эксперименте старый пароль проверяется с новым допустимым сертификатом, поэтому отказ нельзя объяснить только отзывом старого сертификата. + +## Что проверялось на практике + +1. HTTPS проходит с правильным CA; чужой CA/неверное имя сервера отклоняются проверкой сертификата. +2. Каждая API принимает сертификат LB и отвергает отсутствие сертификата, другой CA и запрещённую роль нашего CA. +3. Обработчик не может читать users/sessions/messages, менять владельца/контрольную сумму исходника, публиковать новые задания или очистить очередь. +4. В S3 обработчик может читать исходники и записывать окончательные изображения, но не писать в staging/private, не удалять final и не администрировать buckets. +5. У OpenBao каждая служба читает свой путь; чужой secret и изменение политики дают403. Worker не получает cursor/cache secrets API. +6. Чужой пользователь не читает и не прикрепляет чужое вложение. Поддельный X-User-Id не меняет владельца Bearer-сессии. +7. Вход ограничен общим счётчиком двух API; есть429/Retry-After. Старый Argon2 hash повышается при успешном входе. +8. Отзыв worker identity/пароля, закрытие Bao, восстановление и сохранность файлов проверяются отдельными воспроизводимыми сценариями. +9. Старые возможности сохраняются: upload202, очередь, настоящие варианты изображений, идемпотентность сообщений, лог/trace через весь путь, Grafana с реальными TLS-запросами к трём хранилищам. + +## Как объяснить исследование на пятёрку + +Гипотеза: если обработчику выдать отдельные минимальные права, утечка его доступа не раскроет пароли/сессии/сообщения. После отзыва и замены доступа чистый обработчик сможет завершить ранее принятую работу. + +Исследование сравнивает явно названные запросы. В операторском baseline с общими расширенными credentials чтение password table и администрирование S3 разрешены. С настоящими worker credentials — запрещены. Разрешённая область тоже показана: pipeline SQL, чтение staging, запись final prefix, обработка очереди. Затем старый процесс изолируется, доступ отзывается, пароль и сертификат меняются, новый процесс запускается без пересборки образа. + +Числа и ошибки смотри в REPORT.md и evidence/worker-compromise*.json. Не утверждай нулевой простой: первый опыт сохранил98 успешных сообщений и2 ошибки во время восстановления. Не утверждай, что worker вообще безвреден: он всё ещё может читать изображения всех чатов, портить разрешённые final objects и данные обработки. Это проверенное ограничение ущерба в конкретной модели. + +## Команды демонстрации + +```sh +make up +make test +make test-security +python3 student-tests/security.py +python3 student-tests/compromise.py +python3 student-tests/sealed.py +python3 student-tests/hardening.py +python3 student-tests/telemetry.py +``` + +Запускай сценарии по одному. Для сохранённых результатов достаточно открыть evidence; повторное исследование создаёт новые synthetic data и меняет рабочие credentials. После демонстрации отказа API восстанови обе копии командой docker compose up -d --no-deps --wait api. + +Операторские возможности предыдущей лабы доступны отдельно: + +```sh +docker compose --profile verify run --rm operator cleanup +# По умолчанию dry-run; --apply только для явно проверенной очистки. +docker compose --profile verify run --rm operator replay ATTACHMENT_UUID +docker compose --profile verify run --rm operator reprocess ATTACHMENT_UUID +``` + +## Дополнительные вопросы, которые может задать преподаватель + +**Почему нельзя хранить пароль как SHA256?** Он слишком быстро проверяется перебором. Argon2id расходует память и CPU. SHA256 сессионного случайного256-bit токена решает другую задачу: пароль человек выбирает предсказуемо, токен создаётся генератором случайных чисел. + +**Что даёт соль?** Одинаковые пароли получают разные хеши, заранее подготовленные таблицы не подходят сразу ко всем пользователям. Соль не секрет, хранится рядом с параметрами и результатом. + +**Может ли TLS заменить проверку доступа к чату?** Нет. TLS защищает канал и identity сервиса; membership и действительность пользовательской сессии проверяет API через PG. + +**Зачем отзыв сертификата проверять на новом подключении?** Уже открытое соединение могло пройти проверку раньше. У нас HTTP повторно проверяет serial на запросах, stream соединение ограничено30s, SQL connections при смене пароля завершаются отдельно. Начатый HTTP request ограничен35s. + +**Почему нельзя просто заменить секрет у работающего взломанного процесса?** Злоумышленник может прочитать новую конфигурацию. Поэтому сначала останавливается старый worker, затем выдаётся новый доступ и запускается чистый процесс. + +**Что доказывает scanner0findings?** Что конкретный scanner по конкретной базе не обнаружил известные уязвимости Go-зависимостей в данном коде. Он не доказывает отсутствие ошибок в собственном коде или всех контейнерах. В SCAN_TRIAGE.md разобраны обновления и ограничения. + +**Есть ли отказоустойчивость при потере ноутбука/БД/S3/Bao?** Нет. Один host и одиночные хранилища остаются точками отказа. Шифрование и разные права не создают резервную копию или второй узел. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1624c2c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM golang:1.27.4-alpine3.24 AS build +WORKDIR /src +COPY go.mod go.sum ./ +ARG GOPROXY=https://proxy.golang.org,direct +RUN --mount=type=cache,target=/go/pkg/mod GODEBUG=http2client=0 GOPROXY="$GOPROXY" go mod download +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ +RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server + +FROM build AS tests +RUN apk add --no-cache gcc musl-dev libwebp-tools +RUN --mount=type=cache,target=/go/pkg/mod mkdir -p /opt/gomod && cp -a /go/pkg/mod/. /opt/gomod/ +ENV CGO_ENABLED=1 GOMODCACHE=/opt/gomod +CMD ["go", "test", "-race", "-count=1", "-v", "./..."] + +FROM alpine:3.24.4 +RUN apk add --no-cache libwebp-tools +RUN addgroup -g 10001 app && adduser -D -u 10001 -G app app +COPY --from=build /out/messenger /usr/local/bin/messenger +USER 10001:10001 +ENV APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab +EXPOSE 8080 +HEALTHCHECK --interval=5s --timeout=4s --start-period=3s --retries=3 CMD ["/usr/local/bin/messenger", "healthcheck"] +STOPSIGNAL SIGTERM +ENTRYPOINT ["/usr/local/bin/messenger"] diff --git a/MERGE_REQUEST.md b/MERGE_REQUEST.md new file mode 100644 index 0000000..e811f9d --- /dev/null +++ b/MERGE_REQUEST.md @@ -0,0 +1,11 @@ +ЛР 7 — БВТ 2303 — Крайкин — на 5 + +Автор: Крайкин Глеб Алексеевич, БВТ2303. Цель: 5, трек1 — компрометация worker. + +Работающий мессенджер из собственной ЛР6 переведён на HTTPS с mTLS LB→каждая API; DB/S3/broker/cache/OTel/Grafana/OpenBao связи защищены проверяемым TLS и scoped identities/permissions. Native listeners за gateways доступны только в том же loopback namespace. Добавлены non-dev OpenBao2.7.3/Raft, certificate auth, короткие service tokens, ограниченное поведение при sealed/expiry, ротация SQL secret и leaf, серийный отзыв сертификатов. Worker не получает API cursor/cache secrets, не читает users/sessions/messages и не имеет административных прав S3/broker. + +Реальное исследование показывает baseline с расширенными правами и последствия утечки настоящего worker credential, разрешённые/запрещённые SQL/S3/queue/Bao действия, quarantine/revoke/rotate/replacement и сохранность всех принятых оригиналов без rebuild. Публичные HTTPS smoke/TLS, PG/race/rehash, ACL/logout/expiry, общий rate limit/parallel login budget, последовательный отказ обеих API, полный persistence и настоящая telemetry через Grafana проверены; результаты и ограничения в REPORT.md/evidence. Запуск: make up; make check; make test; make test-security. Секреты создаются локально вне Git/images. + +Модель угроз и фактическая матрица: security/THREAT_MODEL.md, security/TRUST_MATRIX.md. Реальный dependency scan найденные библиотеки исправлены, повторный govulncheck0findings; применимость/границы описаны в SCAN_TRIAGE.md. Контракты API и публичные tests сохранены; предусмотренная заданием trust matrix заполнена. DEFENSE.md содержит понятный рассказ, схемы, словарь и все четыре вопроса README. + +Один host и shared stores остаются SPOF, volume не backup. Компрометация CA/host вне модели; worker всё ещё имеет разрешённые права на все images/pipeline. Cache авторизации до60s, bounded revocation30/35s; статические KV credentials меняются явно, TTL токена не отзывает SQL password. Remote CI не объявляется выполненным. Использован Codex, первичные источники указаны в отчёте. diff --git a/Makefile b/Makefile index 5ad43ad..ca78b9b 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ PYTHON ?= python3 BASE_URL ?= https://localhost:8443 -CA_FILE ?= +CA_FILE ?= $(CURDIR)/certs/ca.crt ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) @@ -31,3 +31,14 @@ test-failover: test-security: $(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +bootstrap: + $(PYTHON) scripts/bootstrap.py +up: + $(PYTHON) scripts/up.py +unseal: + $(PYTHON) scripts/bao_operator.py unseal +down: + docker compose down +test-race: + docker compose --profile verify run --build --rm tests diff --git a/QUICKSTART.md b/QUICKSTART.md new file mode 100644 index 0000000..8fefaf8 --- /dev/null +++ b/QUICKSTART.md @@ -0,0 +1,34 @@ +# Запуск ЛР7 + +Нужны Docker/Compose, Python3.9+, openssl. Go на host не нужен. Всё запускается из этого репозитория. + +```sh +make up +make check +make test +make test-security +python3 student-tests/security.py +make test-race +``` + +`make up` от имени локального оператора создаёт CA/leaf и credentials, собирает приложение, поднимает все сервисы, выполняет миграции и init/unseal/configuration Bao. Секреты/ключи не печатаются и не включаются в Git/images; существующие credentials сохраняются. На повторном запуске истекающие leaf обновляются, процессы пересоздаются с сохранением volumes. + +- REST: https://localhost:8443, trust CA — certs/ca.crt. +- Grafana: https://localhost:3007; anonymous выключен, operator admin password в ignored secrets/grafana_password. +- OpenBao: https://localhost:8207, только оператор; root token и shares в ignored secrets/operator/init.json. +- API/PG/S3/broker/cache/telemetry native ports не опубликованы. + +Браузеру локальный CA автоматически не устанавливается. CLI tests уже используют правильный CA; не отключайте проверку сертификата. `make down` сохраняет volumes. После отдельного рестарта OpenBao он sealed: явный `make unseal` выполняет оператор, приложения shares не получают. + +```sh +python3 student-tests/compromise.py # исследование пятёрки, свои synthetic data +python3 student-tests/sealed.py # ограниченный отказ Bao и expired leaf +python3 scripts/rotate.py rotate worker +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +docker compose up -d --no-deps --wait api # вернуть API после failover +``` + +Все fault/rotation сценарии выполнять последовательно. Они меняют только этот учебный Compose-проект. Не удаляйте рабочие volumes для проверки persistence. Перечень угроз, доверительных границ и пределы отзыва — security/THREAT_MODEL.md и TRUST_MATRIX.md. Рассказ и вопросы — DEFENSE.md; измерения — REPORT.md/evidence. + +Для сохранённых операторских replay/reprocess/cleanup: `docker compose --profile verify run --rm operator cleanup` (dry-run), `operator replay UUID`, `operator reprocess UUID`. Эти одноразовые процессы имеют операторский доступ; runtime worker его не получает. diff --git a/REPORT.md b/REPORT.md index 9801db4..0f265a9 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,94 @@ -# Отчёт — лабораторная 7 +# ЛР7: безопасность работающего мессенджера -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +Крайкин Глеб Алексеевич, БВТ2303. Цель: **5, трек1 — компрометация worker и ограничение последствий**. Эксперименты2 декабря2026, synthetic data, один учебный Docker Desktop host. Оценку выставляет преподаватель после проверки и объяснения. -## Запуск из чистого clone +## Происхождение и запуск -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Skeleton `20afc2c790d3e72f6b7666376c9834c1ced1a405`. Перенесена собственная ЛР6 `d18fe254e983918b58949bbd70ebfaf64085d44a`: две API, общие PG sessions, идемпотентные messages, private S3, durable staging/outbox, Streams, отдельные worker/dispatcher/cleanup, version fencing/retry, OTel/Grafana. Репозиторий самостоятельный. README/COURSE/OpenAPI/публичные tests сохранены; предусмотренный заданием template trust matrix заполнен ссылками на фактическую матрицу, без изменения бизнес-семантики. -## Архитектура и решения +```sh +make up +make check +make validate PYTHON=/путь/к/venv/bin/python # requirements-dev.txt +make test +make test-security +python3 student-tests/security.py +make test-race +``` -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Docker/Compose, Python3.9+, openssl; Go на host не нужен. CA/credentials создаёт оператор, значения скрыты. REST https://localhost:8443; CA certs/ca.crt. Grafana https://localhost:3007, anonymous выключен; OpenBao operator endpoint https://localhost:8207. Все host ports loopback. [QUICKSTART](QUICKSTART.md) — команды отказов/ротации; [DEFENSE](DEFENSE.md) — простой рассказ, схемы, вопросы README; [модель угроз](security/THREAT_MODEL.md), [полная матрица](security/TRUST_MATRIX.md). -## Доказательства критериев +## Реализация границ доверия -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Внешний HTTPS на HAProxy, native mTLS LB→все API. Go TLS server проверяет CA/expiry и exact DNS SANlb.client.lab, client сертификат другого сервиса того же CA отвергается. Public X-Instance-Id — случайный UUID alias жизни API process, hostname/IP не раскрывается. Local health127.0.0.1:8081 обслуживает только live/ready. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +PostgreSQL native TLS/verify-full, hostnossl reject, SCRAM и отдельные ограниченные роли; schema owner существует только в отдельной migration/operator задаче. Общие sessions/ACL проверяются PG, optional profile cache не определяет авторизацию. Worker не имеет SELECT users/sessions/messages, не меняет ownership исходников и не может создавать schema/roles. -## Эксперименты и отказы +Для остальных stores gateway и native backend находятся в одном network namespace. Native listener привязан только127.0.0.1, сетевой listener gateway — TLS/mTLS с exact SAN и разрешением операции. Безопасность включает закрытый локальный hop, а не обещание шифровать память внутри скомпрометированной boundary. Broker: mTLSdispatcher/worker + отдельные Valkey ACL, producer/consumer commands и один stream key. Collector: разные identities API/worker/dispatcher/housekeeping, POST только ingestion paths. Collector→Loki/Tempo и Grafana/Prometheus→stores используют mTLS и разные permissions. Grafana имеет только query rights. Metrics scrape/health/admin включены в матрицу. -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +App/worker/gateways UID10001, read_only, drop ALL capabilities, no-new-privileges; tmpfs для временных файлов/секретов, CPU/RAM limits. Stateful volumes writable, исключения и bootstrap caps названы в матрице. Verify-only compiler container имеет отдельный executable tmpfs и повышенный memory budget; это не runtime API. Docker socket/host network/privileged контейнеров нет. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +## OpenBao и lifecycle -## Ограничения и следующие шаги +OpenBao2.7.3, non-dev, persistent **Raft с одним voter**, декларативный persistent file audit с HMAC значений. Один voter не даёт HA. Оператор создаёт CA365d и leaves24h, выполняет init3shares/threshold2, unseal и policies. CA key, root token/shares находятся только в ignored host operator directory0700/0600, не в Bao/API/worker mounts. Bootstrap доверяет локальному оператору и host; внешнего HSM, distributed share custody и защиты от root host не заявлено. -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Service certificate auth pinned leaf + SAN даёт scoped token60s, только own KVv2 path. Supervisor каждые5s повторно аутентифицируется, читает secrets и отзывает использованный token. Runtime values существуют в памяти/tmpfs, не в image или Compose Env. Последнее успешное чтение даёт ограниченное authorization cache60s; при изменении credentials child перезапускается, при невозможности refresh после deadline останавливается. После обычного рестарта API не нужны operator keys, при sealed Bao новый API не стартует с зашитым запасным секретом. + +KV SQL/S3 credentials статические; TTL токена **не отзывает сам пароль БД**. SQL secret меняется явно: ALTER PASSWORD и terminate старых sessions. Leaf/client reload — на новых handshakes; serial denylist проверяется при handshake и каждом HTTP request, raw stream connection имеет30s absolute deadline, active HTTP request≤35s. Operator certificate auth/token отзываются отдельно. Это bounded revocation, не мгновенный отзыв уже переданных данных. `scripts/rotate.py` меняет SQL password+leaf без rebuild. При инциденте worker сначала карантинируется и заменяется чистым процессом. + +## Пароли и ограничение входа + +Argon2id:64MiB,3passes,2lanes, случайный salt16bytes, hash32bytes. PHC хранит algorithm/version/params/salt/hash. Проверка constant-time; parser старых допустимых параметров ограничен сверху перед выделением памяти. Успешный login повышает старый hash до текущих параметров; интеграционный HTTP/PG test проверяет действительное изменение строки, неверные credentials не создают session. Worker не получает API cursor/cache secrets; dispatcher получает только SQL/broker credentials. Leaf SAN/EKU разделены: worker — только clientAuth, без serverAuth/localhost. Bearer имеет256bit энтропии, в PG только SHA256 digest32bytes, logout и expiry проверяются при каждом запросе. + +Общий для реплик PG admission: максимум12 auth attempts/username/fixed minute,120 global; registration также проходит этот budget. Максимум2 одновременных KDF/API, превышение429 с Retry-After. Измеренный invalid-login KDF/HTTP p50≈73.265ms, max182.701ms в последнем прогоне. Две API показаны в одном rate test; после лимита429. KDF рабочая память ограничена примерно128MiB/API плюс остальная память процесса. Fixed windows допускают двойной burst на границе; глобальный лимит допускает отказ в обслуживании auth при исчерпании бюджета и не является полноценной защитой от distributed DoS. + +## Исследование на5 + +**Гипотеза:** разделение SQL/S3/broker/Bao identities ограничит ущерб при утечке worker credentials до изображения/pipeline, а quarantine+revoke+rotation позволит завершить уже принятые задачи без потери оригиналов. + +Повторяемая методика: `python3 student-tests/compromise.py`. Из работающего worker читаются только его runtime snapshot и leaf, копия сохраняется в ignored operator/test files. Запросы выполняются с этой identity, без CA/root/host/Docker прав. «До разделения» — явно операторский изолированный probe с API SQL credential и S3 root credential, не выдаваемыми реальному worker. Этот baseline показывает риск общего credential; не изображает компрометацию host. + +1. Baseline может читать password table и выполнять S3 bucket administration. +2. Реальный worker читает pipeline и staging своего принятого файла, подключается к своей очереди. Passwords/sessions/messages, owner mutation/schema DROP, staging write/private prefix/bucket admin, XADD/FLUSHALL/other stream и чужой Bao secret запрещены. +3. Worker остановлен,8 uploads приняты через202, идёт background text traffic. Отзываются старый serial, cert auth и выданный token; SQL password заменён с завершением соединений; выдаётся новый leaf и пересоздаётся worker из того же image. +4. Старый cert не подключается к broker/S3; старый SQL password проверяется с **новым доверенным cert**, чтобы доказать именно отзыв secret. Новый worker подключается, все8 accepted files становятся ready и побайтно совпадают. + +**Финальный опыт:** все8 ready за3.823s от начала remediation; background messages80success/0errors; image IDs до/после совпали. Реально выполнены также разрешённый UPDATE execution status и PUT marker в final prefix; изменение checksum/owner и удаление final запрещены. Первый опыт4.101s/98success/2errors сохранён отдельно в `worker-compromise-first.json`; причины двух ошибок в нём не классифицированы, нулевой простой не обещается. Финальные raw allow/deny — `evidence/worker-compromise.json`. Оставшийся ущерб: worker имеет право читать images всех чатов, писать final variants и execution metadata; per-job scoped tokens нет, полнота защиты от malicious worker не заявляется. + +## Проверка expiry/sealed + +`student-tests/sealed.py`: корректный worker SAN с подписанным, но истёкшим leaf отвергнут broker. Bao sealed, одна API перезапущена. Последняя работающая API прекратила business traffic через60.698s, после operator unseal прежняя session/file восстановились за4.324s. Cache60s + polling5s/экспорт/read timeouts объясняют границу; это не бесконечный fallback и не мгновенное выключение по seal. `evidence/sealed-expiry.json` сохраняет actual HTTP timeline. + +## Dependency scan и версии + +Go1.27.4 / Alpine3.24.4. OTel trace/metric/sdk1.47.0, sdk/log1.47.0, HTTP log exporter0.23.0, otelslog0.21.0; pgx5.9.2, x/crypto0.59.0, x/image0.45.0, compress1.20.2; точные indirect pins в go.mod/go.sum. Остальная инфраструктура закреплена compose tags: PG17.6, Valkey8.1.3, HAProxy3.2.6, MinIO RELEASE.2025-09-07T16-13-09Z, Collector0.128.0, Prometheus3.4.1, Loki3.5.1, Tempo2.8.0, Grafana12.0.2. + +Реальный govulncheck1.10.0, Go Vulnerability DB modified2026-11-24: после обновления Go, но до обновления библиотек —423 findings/24 called advisories; после обновления библиотек —0 findings. Raw streams сжаты в `dependency-scan*.json.gz`, читаемое сравнение — `dependency-scan-summary.json`. Команды и разбор применимости — [SCAN_TRIAGE.md](security/SCAN_TRIAGE.md). Это dependency/call-graph scan приложения; OS packages и сторонние контейнеры этим результатом не объявлены свободными от CVE. + +## Границы доказательств и источники + +Single host, одиночные PG/S3/broker/LB/Bao/telemetry stores — SPOF; named volume не backup. Модель не включает root host/CA, автоматический rollover CA, per-job credentials и защиту от произвольного code execution в API. Учебный TLS gateway — собственный небольшой компонент с отрицательными проверками, не независимый security audit. Закрытый loopback hop честно указан. Remote CI не объявляется выполненным. + +Использованы собственные ЛР4–6, контракты преподавателя, Codex для реализации/проверок/объяснений. Первичные источники: [OpenBao cert auth](https://openbao.org/docs/auth/cert/), [declarative audit](https://openbao.org/docs/configuration/audit/), [Raft](https://openbao.org/docs/configuration/storage/raft/), [OWASP password storage](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html), [Go Vulnerability Database](https://vuln.go.dev/), [Go TLS](https://pkg.go.dev/crypto/tls). Автор должен уметь объяснить и изменить решение на защите. + + +## Сводка проверок и нагрузка + +| Проверка | Фактический результат / evidence | +|---|---| +| Неизменённые make check / полный OpenAPI | PASS, check.txt / openapi.txt | +| Public HTTPS smoke / TLS trust | PASS, smoke.txt / public-tls.txt | +| Обе API, broker, Collector, все backend links | Positive и no cert/alien CA/wrong same-CA identity; CA/hostname errors, trust-matrix.json | +| Bao policies и минимальные secrets | Own read, чужой path/policy403, wrong cert role denied, revoked token403; openbao-policy.json | +| Attachment ACL / logout / expiry / forged header | PASS, application-security.json | +| Real PG + race + legacy Argon2 rehash | PASS, race.txt:101 concurrent/idempotent effects, Unicode, actual HTTP rehash, JPEG/PNG EXIF/alpha, child failure classification | +| Parallel login budget | 8 clients /24 attempts:14 real KDF401,10 capacity429 с Retry-After; cgroup lifetime peaks301240320/300556288bytes, cap768MiB/API; auth-budget.json | +| Каждый API отдельно |148success/1error, recovery1.118s;143success/2errors, recovery0.306s; confirmed messages preserved, operations.json | +| Public failover |110success/1failed attempt, recovery1.149s; старый token/data сохранены, failover.txt | +| Полный persistence | PASS через HTTPS, старые token/messages/file, restart всех store/gateway/backend; persistence.txt, окончательное actual StartedAt дополнительно проверяется clean clone | +| Контейнеры и bypass | Реальные UID/read-only/caps/ports/mounts, запрет native ports извне, worker rootfs/other keys denied; hardening.json | +| Реальная наблюдаемость | API→dispatcher→worker→S3/DB trace+Loki correlation; метрики; actual Grafana proxy queries ко всем3 stores, telemetry.json | + +Нагрузка с включёнными TLS/mTLS и telemetry:4 closed-loop clients, без warmup,15.010s;2386success/0errors,158.960 successful RPS, success p50/p95/p99=8.173/129.663/196.474ms. Размеры данных до/после и реальные Docker CPU/RAM observations — load-resources.json. Это растущий набор данных на общей VM, не максимальная capacity и не сравнительное исследование цены TLS. Percentiles включают только успехи, ошибки считаются отдельно, есть coordinated omission. + +Измерения login memory — lifetime peak контейнера после пробы, а не изолированная трассировка allocation этого опыта. Fresh Git clone/new CA/new stores проверяются отдельным student-tests/clean_clone.py; финальный commit и process evidence фиксируются после прогона. Удалённый CI не заявляется выполненным. diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..790f243 --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,290 @@ +package main + +import ( + "context" + "crypto/tls" + "encoding/base64" + "errors" + "fmt" + "github.com/redis/go-redis/v9" + "log/slog" + "mtusi/messenger/internal/database" + "mtusi/messenger/internal/messenger" + "mtusi/messenger/internal/security" + "mtusi/messenger/internal/telemetry" + "net" + "net/http" + "os" + "os/signal" + "strconv" + "strings" + "syscall" + "time" +) + +func env(key, fallback string) string { + if v := os.Getenv(key); v != "" { + return v + } + return fallback +} +func main() { + if err := run(); err != nil { + if errors.Is(err, messenger.ErrInvalidImage) { + os.Exit(65) + } + slog.Error("server failed", "error", err) + os.Exit(1) + } +} +func run() error { + if len(os.Args) == 2 && os.Args[1] == "probe" { + return security.Probe() + } + if len(os.Args) > 1 && (os.Args[1] == "gateway" || os.Args[1] == "supervise") { + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + if os.Args[1] == "gateway" { + if len(os.Args) != 3 { + return fmt.Errorf("gateway config required") + } + return security.Gateway(ctx, os.Args[2]) + } + if len(os.Args) < 3 { + return fmt.Errorf("supervised command required") + } + return security.Supervise(ctx, os.Args[2:]) + } + + if (len(os.Args) == 4 || len(os.Args) == 5) && os.Args[1] == "transform" { + version := 1 + if len(os.Args) == 5 { + v, e := strconv.Atoi(os.Args[4]) + if e != nil { + return e + } + version = v + } + return messenger.Transform(os.Args[2], os.Args[3], version) + } + host := env("APP_HOST", "0.0.0.0") + port := env("APP_PORT", "8080") + p, err := strconv.Atoi(port) + if err != nil || p < 1 || p > 65535 { + return fmt.Errorf("invalid APP_PORT") + } + if len(os.Args) == 2 && os.Args[1] == "healthcheck" { + c := http.Client{Timeout: time.Second} + r, e := c.Get("http://127.0.0.1:8081/health/ready") + if e != nil { + return e + } + defer r.Body.Close() + if r.StatusCode != 200 { + return fmt.Errorf("not ready: %d", r.StatusCode) + } + return nil + } + + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + service := "messenger-api" + if len(os.Args) > 1 { + service = "messenger-" + os.Args[1] + } + if len(os.Args) == 1 || os.Args[1] != "migrate" { + var shutdown func() + var e error + log, shutdown, e = telemetry.Init(context.Background(), service) + if e != nil { + return e + } + defer shutdown() + } + slog.SetDefault(log) + ttl, err := strconv.Atoi(env("SESSION_TTL_SECONDS", "3600")) + if err != nil || ttl < 1 || ttl > 86400 { + return fmt.Errorf("SESSION_TTL_SECONDS must be 1..86400") + } + databaseURL, err := secret("DATABASE_URL_FILE") + if err != nil { + return err + } + startup, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + pool, err := database.Open(startup, databaseURL) + if err != nil { + return err + } + defer pool.Close() + if len(os.Args) == 2 && os.Args[1] == "migrate" { + return database.Migrate(startup, pool) + } + command := "api" + if len(os.Args) > 1 { + command = os.Args[1] + } + var objects *messenger.ObjectStore + if command != "dispatcher" { + storeAccess, err := secret("S3_ACCESS_KEY_ID_FILE") + if err != nil { + return err + } + storeSecret, err := secret("S3_SECRET_ACCESS_KEY_FILE") + if err != nil { + return err + } + objects, err = messenger.NewObjectStore(env("S3_ENDPOINT", "https://s3:9000"), env("S3_BUCKET", "messenger-attachments"), storeAccess, storeSecret) + if err != nil { + return err + } + } + if len(os.Args) > 1 { + command := os.Args[1] + if command == "worker" || command == "dispatcher" || command == "replay" || command == "reprocess" || command == "cleanup" || command == "housekeeping" { + var broker *redis.Client + if command == "worker" || command == "dispatcher" { + brokerURL, e := secret("BROKER_URL_FILE") + if e != nil { + return e + } + opts, e := redis.ParseURL(brokerURL) + if e != nil { + return fmt.Errorf("invalid broker configuration") + } + opts.TLSConfig, e = security.ClientTLS() + if e != nil { + return e + } + opts.MaxRetries = -1 + opts.DialTimeout = time.Second + opts.ReadTimeout = 2 * time.Second + opts.WriteTimeout = 2 * time.Second + broker = redis.NewClient(opts) + defer broker.Close() + } + telemetry.Observe(pool, command == "dispatcher") + pipeline := messenger.NewPipeline(pool, broker, objects, log) + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + switch command { + case "worker": + n, e := strconv.Atoi(env("WORKER_CONCURRENCY", "1")) + if e != nil { + return e + } + return pipeline.RunWorker(ctx, n) + case "dispatcher": + return pipeline.RunDispatcher(ctx) + case "housekeeping": + return pipeline.RunHousekeeping(ctx) + case "cleanup": + return pipeline.Cleanup(ctx, len(os.Args) == 3 && os.Args[2] == "--apply") + case "replay", "reprocess": + if len(os.Args) != 3 { + return fmt.Errorf("expected attachment UUID") + } + return pipeline.Replay(ctx, os.Args[2], command == "reprocess") + } + } + } + cacheURL, err := secret("CACHE_URL_FILE") + if err != nil { + return err + } + cursorKey, err := secret("CURSOR_KEY_FILE") + if err != nil { + return err + } + key, err := base64.RawURLEncoding.DecodeString(cursorKey) + if err != nil || len(key) != 32 { + return fmt.Errorf("invalid cursor key") + } + opts, err := redis.ParseURL(cacheURL) + if err != nil { + return fmt.Errorf("invalid cache configuration") + } + opts.TLSConfig, err = security.ClientTLS() + if err != nil { + return err + } + opts.DialTimeout = 60 * time.Millisecond + opts.ReadTimeout = 60 * time.Millisecond + opts.WriteTimeout = 60 * time.Millisecond + opts.PoolTimeout = 60 * time.Millisecond + opts.ContextTimeoutEnabled = true + opts.MaxRetries = -1 + opts.PoolSize = 10 + cache := redis.NewClient(opts) + defer cache.Close() + telemetry.Observe(pool, false) + api := messenger.New(pool, cache, key, ttl, log) + api.SetObjectStore(objects) + srv := &http.Server{Addr: net.JoinHostPort(host, port), Handler: api, ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 35 * time.Second, WriteTimeout: 35 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10} + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + // Only loopback, only health routes; it cannot bypass mTLS for business API. + health := &http.Server{Addr: "127.0.0.1:8081", ReadHeaderTimeout: time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/health/live" && r.URL.Path != "/health/ready" { + http.NotFound(w, r) + return + } + api.ServeHTTP(w, r) + })} + go health.ListenAndServe() + defer health.Close() + srv.IdleTimeout = 2 * time.Second + done := make(chan error, 1) + go func() { + log.Info("listening", "address", srv.Addr, "session_store", "postgres", "profile_cache", "valkey", "environment", env("APP_ENV", "lab")) + tc, e := security.ServerTLS([]string{"lb"}) + if e != nil { + done <- e + return + } + srv.Handler = security.AuthorizeHTTP(tc, api) + listener, e := tls.Listen("tcp", srv.Addr, tc) + if e != nil { + done <- e + return + } + done <- srv.Serve(listener) + }() + select { + case err := <-done: + return err + case <-ctx.Done(): + } + start := time.Now() + api.Stop() + log.Info("shutdown started") + shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := srv.Shutdown(shutdown); err != nil { + _ = srv.Close() + return err + } + err = <-done + if !errors.Is(err, http.ErrServerClosed) { + return err + } + log.Info("shutdown completed", "duration_ms", time.Since(start).Milliseconds()) + return nil +} + +func secret(name string) (string, error) { + if value, ok := security.RuntimeSecret(name); ok { + if value == "" { + return "", fmt.Errorf("missing runtime secret %s", name) + } + return value, nil + } + path := os.Getenv(name) + if path == "" { + return "", fmt.Errorf("missing %s", name) + } + raw, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("cannot read %s", name) + } + return strings.TrimSpace(string(raw)), nil +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..7f76502 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,1075 @@ +--- +name: mtusi-lab7-kraykin +services: + broker: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.5 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - gateway + - "/config/gateway.json" + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: broker + volumes: + - "./certs/private/broker:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + - "./infra/tls/broker.json:/config/gateway.json:ro" + healthcheck: + test: + - CMD-SHELL + - kill -0 1 + interval: 2s + timeout: 1s + retries: 3 + cache: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.5 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - gateway + - "/config/gateway.json" + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: cache + volumes: + - "./certs/private/cache:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + - "./infra/tls/cache.json:/config/gateway.json:ro" + healthcheck: + test: + - CMD-SHELL + - kill -0 1 + interval: 2s + timeout: 1s + retries: 3 + s3: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.5 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - gateway + - "/config/gateway.json" + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: s3 + volumes: + - "./certs/private/s3:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + - "./infra/tls/s3.json:/config/gateway.json:ro" + healthcheck: + test: + - CMD-SHELL + - kill -0 1 + interval: 2s + timeout: 1s + retries: 3 + collector: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.5 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - gateway + - "/config/gateway.json" + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: collector + volumes: + - "./certs/private/collector:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + - "./infra/tls/collector.json:/config/gateway.json:ro" + healthcheck: + test: + - CMD-SHELL + - kill -0 1 + interval: 2s + timeout: 1s + retries: 3 + prometheus: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.5 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - gateway + - "/config/gateway.json" + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: prometheus + volumes: + - "./certs/private/prometheus:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + - "./infra/tls/prometheus.json:/config/gateway.json:ro" + healthcheck: + test: + - CMD-SHELL + - kill -0 1 + interval: 2s + timeout: 1s + retries: 3 + loki: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.5 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - gateway + - "/config/gateway.json" + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: loki + volumes: + - "./certs/private/loki:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + - "./infra/tls/loki.json:/config/gateway.json:ro" + healthcheck: + test: + - CMD-SHELL + - kill -0 1 + interval: 2s + timeout: 1s + retries: 3 + tempo: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.5 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - gateway + - "/config/gateway.json" + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: tempo + volumes: + - "./certs/private/tempo:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + - "./infra/tls/tempo.json:/config/gateway.json:ro" + healthcheck: + test: + - CMD-SHELL + - kill -0 1 + interval: 2s + timeout: 1s + retries: 3 + grafana: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.5 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - gateway + - "/config/gateway.json" + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: grafana + volumes: + - "./certs/private/grafana:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + - "./infra/tls/grafana.json:/config/gateway.json:ro" + healthcheck: + test: + - CMD-SHELL + - kill -0 1 + interval: 2s + timeout: 1s + retries: 3 + ports: + - 127.0.0.1:${GRAFANA_PORT:-3007}:3000 + postgres: + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 2 + mem_limit: 512m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: postgres:17.6-alpine + entrypoint: + - "/bin/sh" + - "/config/postgres-start.sh" + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: "/run/secrets/postgres_password" + secrets: + - postgres_password + volumes: + - postgres_data:/var/lib/postgresql/data + - "./infra/postgres-start.sh:/config/postgres-start.sh:ro" + - "./infra/pg_hba.conf:/config/pg_hba.conf:ro" + - "./certs/private/postgres:/run/tls:ro" + tmpfs: + - "/tmp:rw,nosuid,noexec,size=16m" + - "/var/run/postgresql:rw,size=16m" + cap_add: + - CHOWN + - FOWNER + - DAC_OVERRIDE + - SETGID + - SETUID + healthcheck: + test: + - CMD-SHELL + - pg_isready -U messenger -d messenger + interval: 1s + timeout: 2s + retries: 30 + read_only: true + broker-store: + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 0.5 + mem_limit: 256m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: valkey/valkey:8.1.3-alpine + network_mode: service:broker + command: + - valkey-server + - "/run/secrets/broker_config" + secrets: + - broker_config + depends_on: + broker: + condition: service_started + volumes: + - broker_data:/data + read_only: true + tmpfs: + - "/tmp:rw,size=16m" + user: 999:1000 + cache-store: + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 0.5 + mem_limit: 256m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: valkey/valkey:8.1.3-alpine + network_mode: service:cache + command: + - valkey-server + - "/run/secrets/valkey_config" + secrets: + - valkey_config + depends_on: + cache: + condition: service_started + volumes: [] + read_only: true + tmpfs: + - "/tmp:rw,size=16m" + user: 999:1000 + s3-store: + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 1 + mem_limit: 512m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: quay.io/minio/minio:RELEASE.2025-09-07T16-13-09Z + network_mode: service:s3 + command: + - server + - "/data" + - "--address" + - 127.0.0.1:9001 + - "--console-address" + - 127.0.0.1:9002 + environment: + MINIO_ROOT_USER_FILE: "/run/secrets/s3_root_user" + MINIO_ROOT_PASSWORD_FILE: "/run/secrets/s3_root_password" + MINIO_BROWSER: 'off' + secrets: + - s3_root_user + - s3_root_password + volumes: + - s3_data:/data + depends_on: + s3: + condition: service_started + read_only: true + tmpfs: + - "/tmp:rw,size=16m" + - "/root/.minio:rw,size=16m" + s3-init: + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 0.5 + mem_limit: 256m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: minio/mc:RELEASE.2025-08-13T08-35-41Z + network_mode: service:s3 + entrypoint: + - "/bin/sh" + - "/config/s3-init.sh" + volumes: + - "./infra/s3:/config:ro" + - "./secrets/operator/s3-users.sh:/run/operator/users.sh:ro" + secrets: + - s3_root_user + - s3_root_password + depends_on: + s3-store: + condition: service_started + tmpfs: + - "/tmp:rw,size=16m" + environment: + MC_CONFIG_DIR: "/tmp/mc" + restart: 'no' + openbao: + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 0.5 + mem_limit: 256m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: ghcr.io/openbao/openbao:2.7.3 + entrypoint: + - bao + command: + - server + - "-config=/bao/config/server.hcl" + environment: + BAO_ADDR: https://127.0.0.1:8200 + BAO_CACERT: "/run/tls/ca.crt" + volumes: + - "./infra/openbao/server.hcl:/bao/config/server.hcl:ro" + - "./certs/private/openbao:/run/tls:ro" + - bao_data:/bao/data + - bao_audit:/bao/audit + ports: + - 127.0.0.1:${BAO_PORT:-8207}:8200 + read_only: true + tmpfs: + - "/tmp:rw,size=16m" + user: 10001:10001 + depends_on: + storage-init: + condition: service_completed_successfully + migrate: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.5 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - migrate + environment: + DATABASE_URL_FILE: "/run/secrets/migrate_database_url" + OTEL_SDK_DISABLED: 'true' + volumes: + - "./certs/private/migrator:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + secrets: + - migrate_database_url + depends_on: + postgres: + condition: service_healthy + restart: 'no' + healthcheck: + disable: true + api: + image: mtusi-messenger:lab7 + build: "." + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 1 + mem_limit: 768m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - supervise + - api + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: api + APP_PORT: '8080' + SESSION_TTL_SECONDS: "${SESSION_TTL_SECONDS:-3600}" + BAO_ADDR: https://openbao:8200 + S3_ENDPOINT: https://s3:9000 + S3_BUCKET: messenger-attachments + OTEL_EXPORTER_OTLP_ENDPOINT: https://collector:4318 + DB_POOL_MAX: '10' + GOMEMLIMIT: 600MiB + WORKER_CONCURRENCY: "${WORKER_CONCURRENCY:-1}" + volumes: + - "./certs/private/api:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + depends_on: + migrate: + condition: service_completed_successfully + openbao: + condition: service_started + s3-init: + condition: service_completed_successfully + stop_grace_period: 10s + deploy: + replicas: "${API_REPLICAS:-2}" + worker: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 1 + mem_limit: 1024m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - supervise + - worker + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: worker + APP_PORT: '8080' + SESSION_TTL_SECONDS: "${SESSION_TTL_SECONDS:-3600}" + BAO_ADDR: https://openbao:8200 + S3_ENDPOINT: https://s3:9000 + S3_BUCKET: messenger-attachments + OTEL_EXPORTER_OTLP_ENDPOINT: https://collector:4318 + DB_POOL_MAX: '4' + GOMEMLIMIT: 600MiB + WORKER_CONCURRENCY: "${WORKER_CONCURRENCY:-1}" + volumes: + - "./certs/private/worker:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + depends_on: + migrate: + condition: service_completed_successfully + openbao: + condition: service_started + s3-init: + condition: service_completed_successfully + stop_grace_period: 10s + healthcheck: + test: + - CMD-SHELL + - kill -0 1 + interval: 2s + timeout: 1s + retries: 3 + dispatcher: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.25 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - supervise + - dispatcher + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: dispatcher + APP_PORT: '8080' + SESSION_TTL_SECONDS: "${SESSION_TTL_SECONDS:-3600}" + BAO_ADDR: https://openbao:8200 + S3_ENDPOINT: https://s3:9000 + S3_BUCKET: messenger-attachments + OTEL_EXPORTER_OTLP_ENDPOINT: https://collector:4318 + DB_POOL_MAX: '4' + GOMEMLIMIT: 600MiB + WORKER_CONCURRENCY: "${WORKER_CONCURRENCY:-1}" + volumes: + - "./certs/private/dispatcher:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + depends_on: + migrate: + condition: service_completed_successfully + openbao: + condition: service_started + s3-init: + condition: service_completed_successfully + stop_grace_period: 10s + healthcheck: + test: + - CMD-SHELL + - kill -0 1 + interval: 2s + timeout: 1s + retries: 3 + housekeeping: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.25 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + command: + - supervise + - housekeeping + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: housekeeping + APP_PORT: '8080' + SESSION_TTL_SECONDS: "${SESSION_TTL_SECONDS:-3600}" + BAO_ADDR: https://openbao:8200 + S3_ENDPOINT: https://s3:9000 + S3_BUCKET: messenger-attachments + OTEL_EXPORTER_OTLP_ENDPOINT: https://collector:4318 + DB_POOL_MAX: '4' + GOMEMLIMIT: 600MiB + WORKER_CONCURRENCY: "${WORKER_CONCURRENCY:-1}" + volumes: + - "./certs/private/housekeeping:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + depends_on: + migrate: + condition: service_completed_successfully + openbao: + condition: service_started + s3-init: + condition: service_completed_successfully + stop_grace_period: 10s + healthcheck: + test: + - CMD-SHELL + - kill -0 1 + interval: 2s + timeout: 1s + retries: 3 + lb: + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 1 + mem_limit: 128m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: haproxy:3.2.6-alpine + user: 10001:10001 + read_only: true + tmpfs: + - "/tmp:rw,size=16m" + volumes: + - "./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro" + - "./certs/private/lb:/run/tls:ro" + ports: + - 127.0.0.1:${APP_PORT:-8443}:8443 + depends_on: + api: + condition: service_started + collector-store: + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 0.5 + mem_limit: 256m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: otel/opentelemetry-collector-contrib:0.128.0 + network_mode: service:collector + command: + - "--config=/etc/otelcol/config.yaml" + volumes: + - "./infra/otel/collector.yaml:/etc/otelcol/config.yaml:ro" + - "./certs/private/collector:/run/tls:ro" + depends_on: + collector: + condition: service_started + read_only: true + prometheus-store: + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 0.5 + mem_limit: 256m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: prom/prometheus:v3.4.1 + network_mode: service:prometheus + command: + - "--web.listen-address=127.0.0.1:9091" + - "--config.file=/etc/prometheus/prometheus.yaml" + - "--storage.tsdb.retention.time=24h" + - "--storage.tsdb.retention.size=512MB" + volumes: + - "./infra/prometheus:/etc/prometheus:ro" + - "./certs/private/prometheus:/run/tls:ro" + - prometheus_data:/prometheus + depends_on: + prometheus: + condition: service_started + read_only: true + loki-store: + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 0.5 + mem_limit: 256m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: grafana/loki:3.5.1 + network_mode: service:loki + command: + - "-config.file=/etc/loki/local-config.yaml" + volumes: + - "./infra/loki/loki.yaml:/etc/loki/local-config.yaml:ro" + - loki_data:/loki + depends_on: + loki: + condition: service_started + read_only: true + tmpfs: + - "/tmp:rw,size=16m" + tempo-store: + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 0.5 + mem_limit: 256m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: grafana/tempo:2.8.0 + network_mode: service:tempo + command: + - "-config.file=/etc/tempo.yaml" + volumes: + - "./infra/tempo/tempo.yaml:/etc/tempo.yaml:ro" + - tempo_data:/var/tempo + depends_on: + tempo: + condition: service_started + read_only: true + tmpfs: + - "/tmp:rw,size=16m" + grafana-store: + entrypoint: + - "/bin/sh" + - "/config/grafana-start.sh" + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + cpus: 0.5 + mem_limit: 256m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + image: grafana/grafana:12.0.2 + network_mode: service:grafana + environment: + GF_SERVER_HTTP_ADDR: 127.0.0.1 + GF_SERVER_HTTP_PORT: '3001' + GF_AUTH_ANONYMOUS_ENABLED: 'false' + GF_USERS_ALLOW_SIGN_UP: 'false' + GF_SECURITY_ADMIN_PASSWORD__FILE: "/run/secrets/grafana_password" + GF_PLUGINS_PREINSTALL_DISABLED: 'true' + GF_ANALYTICS_REPORTING_ENABLED: 'false' + GF_ANALYTICS_CHECK_FOR_UPDATES: 'false' + secrets: + - grafana_password + volumes: + - "./infra/grafana-start.sh:/config/grafana-start.sh:ro" + - "./infra/grafana/provisioning:/etc/grafana/provisioning:ro" + - "./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro" + - "./certs/private/grafana:/run/tls:ro" + - grafana_data:/var/lib/grafana + depends_on: + grafana: + condition: service_started + read_only: true + tmpfs: + - "/tmp:rw,size=16m" + probe: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: &1 + - ALL + security_opt: &2 + - no-new-privileges:true + tmpfs: &3 + - "/tmp:rw,noexec,nosuid,size=128m,mode=1777" + - "/run/runtime:rw,noexec,nosuid,size=1m,uid=10001,gid=10001,mode=700" + cpus: 0.5 + mem_limit: 256m + logging: &4 + driver: json-file + options: + max-size: 10m + max-file: '3' + profiles: &5 + - verify + command: + - probe + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: operator + OTEL_SDK_DISABLED: 'true' + volumes: + - "./certs/private/operator:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + - "./certs/private:/fixtures:ro" + - "./secrets/operator:/operator:ro" + healthcheck: &6 + disable: true + tests: + image: mtusi-messenger-tests:lab7 + build: + context: "." + target: tests + user: '0:0' + read_only: false + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + tmpfs: + - "/tmp:rw,exec,nosuid,size=1536m" + cpus: 2 + mem_limit: 2048m + logging: + driver: json-file + options: + max-size: 10m + max-file: '3' + profiles: + - verify + entrypoint: + - go + command: + - test + - "-race" + - "-count=1" + - "-v" + - "./..." + environment: + GOMAXPROCS: '2' + GOFLAGS: "-p=2" + DATABASE_TEST_URL_FILE: "/run/secrets/migrate_database_url" + secrets: + - migrate_database_url + volumes: + - "./certs/private/migrator:/run/tls:ro" + - go_test_cache:/root/.cache/go-build + healthcheck: + disable: true + storage-init: + image: alpine:3.24.4 + user: '0:0' + read_only: true + cap_drop: + - ALL + cap_add: + - CHOWN + - DAC_OVERRIDE + security_opt: + - no-new-privileges:true + command: + - chown + - "-R" + - 10001:10001 + - "/bao/data" + - "/bao/audit" + volumes: + - bao_data:/bao/data + - bao_audit:/bao/audit + cpus: 0.25 + mem_limit: 32m + restart: 'no' + operator: + image: mtusi-messenger:lab7 + user: 10001:10001 + read_only: true + cap_drop: *1 + security_opt: *2 + tmpfs: *3 + cpus: 0.5 + mem_limit: 256m + logging: *4 + profiles: *5 + command: + - cleanup + environment: + TLS_CA_FILE: "/run/tls/ca.crt" + TLS_CERT_FILE: "/run/tls/cert.crt" + TLS_KEY_FILE: "/run/tls/key.key" + TLS_REVOCATIONS_FILE: "/config/revoked.json" + SERVICE_ID: operator + OTEL_SDK_DISABLED: 'true' + RUNTIME_SECRET_FILE: "/operator/admin-runtime.json" + S3_ENDPOINT: https://s3:9000 + volumes: + - "./certs/private/operator:/run/tls:ro" + - "./infra/tls/revoked.json:/config/revoked.json:ro" + - "./secrets/operator/admin-runtime.json:/operator/admin-runtime.json:ro" + healthcheck: *6 +secrets: + postgres_password: + file: "./secrets/postgres_password" + migrate_database_url: + file: "./secrets/migrate_database_url" + s3_root_user: + file: "./secrets/s3_root_user" + s3_root_password: + file: "./secrets/s3_root_password" + grafana_password: + file: "./secrets/grafana_password" + broker_config: + file: "./secrets/broker_config" + valkey_config: + file: "./secrets/valkey_config" +volumes: + postgres_data: + s3_data: + broker_data: + bao_data: + bao_audit: + prometheus_data: + loki_data: + tempo_data: + grafana_data: + go_test_cache: diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a977..a665375 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -1,21 +1,21 @@ -# Матрица доверия — заполнить в решении lab7 +# Матрица доверия — решение ЛР7 Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. | Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | | --- | --- | --- | --- | -| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | -| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | -| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | -| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO | -| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | -| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO | -| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO | -| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO | -| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO | -| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO | -| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO | -| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO | +| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | +| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | +| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | +| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | +| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | +| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | +| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | +| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | +| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | +| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | +| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | +| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py | Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. @@ -35,3 +35,5 @@ OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии. Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. + +Матрица решения детально заполнена в [security/TRUST_MATRIX.md](../security/TRUST_MATRIX.md), модель угроз — [THREAT_MODEL.md](../security/THREAT_MODEL.md). API→broker: N/A, API использует transactional outbox; межузловая replication не добавлялась. Остальные строки покрыты TLS/mTLS и отрицательными проверками указанного сценария. diff --git a/evidence/application-security.json b/evidence/application-security.json new file mode 100644 index 0000000..7e690c6 --- /dev/null +++ b/evidence/application-security.json @@ -0,0 +1,9 @@ +{ + "attachment_acl": true, + "forged_identity_denied": true, + "cross_chat_attachment_denied": true, + "expired_session_denied": true, + "logout_denied": true, + "hashes_only": true, + "token_hash_bytes": true +} diff --git a/evidence/auth-budget.json b/evidence/auth-budget.json new file mode 100644 index 0000000..b4a7f8a --- /dev/null +++ b/evidence/auth-budget.json @@ -0,0 +1,260 @@ +{ + "scope": "shared username bucket on two real API replicas, unknown username KDF, sequential invalid attempts", + "attempts": [ + { + "status": 401, + "seconds": 0.15739225, + "instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f", + "retry_after": null + }, + { + "status": 401, + "seconds": 0.18270066599999998, + "instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5", + "retry_after": null + }, + { + "status": 401, + "seconds": 0.11214866600000001, + "instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f", + "retry_after": null + }, + { + "status": 401, + "seconds": 0.070015041, + "instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5", + "retry_after": null + }, + { + "status": 401, + "seconds": 0.11456191599999999, + "instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f", + "retry_after": null + }, + { + "status": 401, + "seconds": 0.07591387500000002, + "instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5", + "retry_after": null + }, + { + "status": 401, + "seconds": 0.06304100000000001, + "instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f", + "retry_after": null + }, + { + "status": 401, + "seconds": 0.06627162500000006, + "instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5", + "retry_after": null + }, + { + "status": 401, + "seconds": 0.09612395900000004, + "instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f", + "retry_after": null + }, + { + "status": 401, + "seconds": 0.07061700000000004, + "instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5", + "retry_after": null + }, + { + "status": 401, + "seconds": 0.06350758299999981, + "instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f", + "retry_after": null + }, + { + "status": 401, + "seconds": 0.07031729200000014, + "instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5", + "retry_after": null + }, + { + "status": 429, + "seconds": 0.006560708999999942, + "instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f", + "retry_after": "60" + }, + { + "status": 429, + "seconds": 0.007485750000000069, + "instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5", + "retry_after": "60" + }, + { + "status": 429, + "seconds": 0.006046124999999902, + "instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f", + "retry_after": "60" + }, + { + "status": 429, + "seconds": 0.006384166999999996, + "instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5", + "retry_after": "60" + }, + { + "status": 429, + "seconds": 0.004841917000000029, + "instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f", + "retry_after": "60" + }, + { + "status": 429, + "seconds": 0.004661250000000061, + "instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5", + "retry_after": "60" + } + ], + "kdf_parameters": { + "memory_kib": 65536, + "passes": 3, + "lanes": 2, + "slots_per_api": 2 + }, + "successful_kdf_observed_ms": { + "p50": 73.26543750000003, + "max": 182.70066599999998 + }, + "limits": { + "per_username_per_fixed_minute": 12, + "global_auth_per_fixed_minute": 120, + "boundary_max_two_adjacent_windows": 24 + }, + "bound": "2*64MiB KDF working memory per API plus image/process memory; excess concurrent KDF admission returns429", + "parallel_login_probe": { + "concurrency": 8, + "attempts": 24, + "responses": [ + { + "status": 401, + "seconds": 0.234659, + "retry_after": null + }, + { + "status": 401, + "seconds": 0.181604, + "retry_after": null + }, + { + "status": 401, + "seconds": 0.676529, + "retry_after": null + }, + { + "status": 401, + "seconds": 0.18093, + "retry_after": null + }, + { + "status": 401, + "seconds": 0.553548, + "retry_after": null + }, + { + "status": 401, + "seconds": 0.565564, + "retry_after": null + }, + { + "status": 401, + "seconds": 0.605484, + "retry_after": null + }, + { + "status": 401, + "seconds": 0.231737, + "retry_after": null + }, + { + "status": 429, + "seconds": 0.185875, + "retry_after": "1" + }, + { + "status": 429, + "seconds": 0.084691, + "retry_after": "1" + }, + { + "status": 429, + "seconds": 0.106126, + "retry_after": "1" + }, + { + "status": 429, + "seconds": 0.13174, + "retry_after": "1" + }, + { + "status": 429, + "seconds": 0.099201, + "retry_after": "1" + }, + { + "status": 401, + "seconds": 0.40589, + "retry_after": null + }, + { + "status": 429, + "seconds": 0.193023, + "retry_after": "1" + }, + { + "status": 429, + "seconds": 0.197215, + "retry_after": "1" + }, + { + "status": 401, + "seconds": 0.316612, + "retry_after": null + }, + { + "status": 401, + "seconds": 0.39436, + "retry_after": null + }, + { + "status": 401, + "seconds": 0.39396, + "retry_after": null + }, + { + "status": 429, + "seconds": 0.26043, + "retry_after": "1" + }, + { + "status": 429, + "seconds": 0.195508, + "retry_after": "1" + }, + { + "status": 401, + "seconds": 0.34017, + "retry_after": null + }, + { + "status": 401, + "seconds": 0.296132, + "retry_after": null + }, + { + "status": 429, + "seconds": 0.240738, + "retry_after": "1" + } + ], + "api_container_lifetime_memory_peak_bytes_after_probe": [ + 301240320, + 300556288 + ], + "memory_scope": "cgroup lifetime peak, not an isolated allocation trace; API cap768MiB each" + } +} diff --git a/evidence/auth-budget.txt b/evidence/auth-budget.txt new file mode 100644 index 0000000..b56362e --- /dev/null +++ b/evidence/auth-budget.txt @@ -0,0 +1 @@ +PASS: shared two-replica rate limit, real concurrent KDF admission429/Retry-After and measured memory budget diff --git a/evidence/build.txt b/evidence/build.txt new file mode 100644 index 0000000..aa1a355 --- /dev/null +++ b/evidence/build.txt @@ -0,0 +1,152 @@ +Compose can now delegate builds to bake for better performance. + To do so, set COMPOSE_BAKE=true. +#0 building with "desktop-linux" instance using docker driver + +#1 [tests internal] load build definition from Dockerfile +#1 transferring dockerfile: 1.11kB done +#1 DONE 0.0s + +#2 [api internal] load build definition from Dockerfile +#2 transferring dockerfile: 1.11kB done +#2 DONE 0.0s + +#3 [api internal] load metadata for docker.io/library/alpine:3.24.4 +#3 DONE 0.0s + +#4 [tests internal] load metadata for docker.io/library/golang:1.27.4-alpine3.24 +#4 DONE 0.0s + +#5 [tests internal] load .dockerignore +#5 transferring context: 196B done +#5 DONE 0.0s + +#6 [api internal] load .dockerignore +#6 transferring context: 196B done +#6 DONE 0.0s + +#7 [api stage-2 1/4] FROM docker.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf +#7 resolve docker.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf 0.0s done +#7 DONE 0.0s + +#8 [tests build 1/7] FROM docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 +#8 resolve docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 0.0s done +#8 DONE 0.0s + +#9 [api internal] load build context +#9 transferring context: 37.30kB done +#9 DONE 0.0s + +#10 [tests internal] load build context +#10 transferring context: 37.30kB done +#10 DONE 0.0s + +#11 [api build 3/7] COPY go.mod go.sum ./ +#11 CACHED + +#12 [api build 2/7] WORKDIR /src +#12 CACHED + +#13 [api build 4/7] RUN --mount=type=cache,target=/go/pkg/mod GODEBUG=http2client=0 GOPROXY="https://proxy.golang.org,direct" go mod download +#13 CACHED + +#14 [tests build 5/7] COPY cmd/ ./cmd/ +#14 CACHED + +#15 [tests build 6/7] COPY internal/ ./internal/ +#15 DONE 0.0s + +#16 [api build 7/7] RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server +#16 DONE 10.4s + +#17 [tests build 7/7] RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server +#17 CACHED + +#12 [tests build 2/7] WORKDIR /src +#12 CACHED + +#18 [tests build 4/7] RUN --mount=type=cache,target=/go/pkg/mod GODEBUG=http2client=0 GOPROXY="https://proxy.golang.org,direct" go mod download +#18 CACHED + +#19 [tests build 6/7] COPY internal/ ./internal/ +#19 CACHED + +#20 [tests build 5/7] COPY cmd/ ./cmd/ +#20 CACHED + +#21 [tests build 3/7] COPY go.mod go.sum ./ +#21 CACHED + +#22 [api stage-2 2/4] RUN apk add --no-cache libwebp-tools +#22 CACHED + +#23 [api stage-2 3/4] RUN addgroup -g 10001 app && adduser -D -u 10001 -G app app +#23 CACHED + +#24 [api stage-2 4/4] COPY --from=build /out/messenger /usr/local/bin/messenger +#24 DONE 0.0s + +#25 [api] exporting to image +#25 exporting layers +#25 exporting layers 0.5s done +#25 exporting manifest sha256:4d8a2b0fbbb6c5c88d1dcd6979f46f2f35fa2ccdbe72650944f8a5b42ac3f4b9 +#25 exporting manifest sha256:4d8a2b0fbbb6c5c88d1dcd6979f46f2f35fa2ccdbe72650944f8a5b42ac3f4b9 done +#25 exporting config sha256:4e044b8aad682a9b15c59ebd0eded9e519c5f22ba5b72c020d2f00cb73f6c739 done +#25 exporting attestation manifest sha256:069d2d05259e5e1c6f7e52bbd6419527412d160cb3bd4601a631c6f4f93fa6fe done +#25 exporting manifest list sha256:0cc4658eae5fb71ea4a44ffb5584d5d1c650eda5887702e992c65552c8f789db done +#25 naming to docker.io/library/mtusi-messenger:lab7 done +#25 unpacking to docker.io/library/mtusi-messenger:lab7 0.1s done +#25 DONE 0.7s + +#26 [tests tests 1/2] RUN apk add --no-cache gcc musl-dev libwebp-tools +#26 ... + +#27 [api] resolving provenance for metadata file +#27 DONE 0.0s + +#26 [tests tests 1/2] RUN apk add --no-cache gcc musl-dev libwebp-tools +#26 1.175 ( 1/22) Installing libgcc (15.2.0-r5) +#26 1.266 ( 2/22) Installing jansson (2.15.0-r0) +#26 1.356 ( 3/22) Installing libstdc++ (15.2.0-r5) +#26 1.470 ( 4/22) Installing zstd-libs (1.6.0-r1) +#26 1.567 ( 5/22) Installing binutils (2.45.1-r1) +#26 1.775 ( 6/22) Installing libgcc-static (15.2.0-r5) +#26 1.908 ( 7/22) Installing libgomp (15.2.0-r5) +#26 1.997 ( 8/22) Installing libatomic (15.2.0-r5) +#26 2.079 ( 9/22) Installing gmp (6.3.0-r4) +#26 2.173 (10/22) Installing isl26 (0.26-r2) +#26 2.294 (11/22) Installing mpfr4 (4.2.2-r0) +#26 2.397 (12/22) Installing mpc1 (1.3.1-r1) +#26 2.481 (13/22) Installing gcc (15.2.0-r5) +#26 7.161 (14/22) Installing giflib (5.2.2-r2) +#26 7.244 (15/22) Installing libjpeg-turbo (3.1.3-r0) +#26 7.356 (16/22) Installing libpng (1.6.59-r0) +#26 7.451 (17/22) Installing libsharpyuv (1.6.0-r0) +#26 7.537 (18/22) Installing libwebp (1.6.0-r0) +#26 7.648 (19/22) Installing libwebpdemux (1.6.0-r0) +#26 7.731 (20/22) Installing libwebpmux (1.6.0-r0) +#26 7.817 (21/22) Installing libwebp-tools (1.6.0-r0) +#26 7.913 (22/22) Installing musl-dev (1.2.6-r3) +#26 8.549 Executing busybox-1.37.0-r31.trigger +#26 8.559 OK: 176.0 MiB in 39 packages +#26 DONE 8.7s + +#28 [tests tests 2/2] RUN --mount=type=cache,target=/go/pkg/mod mkdir -p /opt/gomod && cp -a /go/pkg/mod/. /opt/gomod/ +#28 DONE 2.9s + +#29 [tests] exporting to image +#29 exporting layers +#29 exporting layers 11.2s done +#29 exporting manifest sha256:665afab75275fe67682c6aff3ceac03216c264383bcee0f187bbc722ee677a66 +#29 exporting manifest sha256:665afab75275fe67682c6aff3ceac03216c264383bcee0f187bbc722ee677a66 0.0s done +#29 exporting config sha256:fde951401451ecb2a9a786d48591dc2a74390a3de35021f179e91ecf9b35c915 0.0s done +#29 exporting attestation manifest sha256:a5e086eb0a82ac80d98423f2730f3ac5eadb25c998c9c62c4cb454d30435bf31 0.0s done +#29 exporting manifest list sha256:a7539c215a62520998a8acd12cc27cf15e89c335debde91f47afd650d9abb779 done +#29 naming to docker.io/library/mtusi-messenger-tests:lab7 done +#29 unpacking to docker.io/library/mtusi-messenger-tests:lab7 +#29 unpacking to docker.io/library/mtusi-messenger-tests:lab7 3.2s done +#29 DONE 14.6s + +#30 [tests] resolving provenance for metadata file +#30 DONE 0.0s + api Built + tests Built diff --git a/evidence/check.txt b/evidence/check.txt new file mode 100644 index 0000000..9a55330 --- /dev/null +++ b/evidence/check.txt @@ -0,0 +1,2 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/evidence/compromise.txt b/evidence/compromise.txt new file mode 100644 index 0000000..3ec526a --- /dev/null +++ b/evidence/compromise.txt @@ -0,0 +1,2 @@ +Rotated worker SQL secret and leaf certificate; previous serial denied; images unchanged; private values hidden. +PASS: bounded worker compromise, before/after least privilege, actual identity/SQL revocation, fresh worker restored all accepted bytes; no image rebuild diff --git a/evidence/dependency-scan-initial.json.gz b/evidence/dependency-scan-initial.json.gz new file mode 100644 index 0000000..e5f4088 Binary files /dev/null and b/evidence/dependency-scan-initial.json.gz differ diff --git a/evidence/dependency-scan-summary.json b/evidence/dependency-scan-summary.json new file mode 100644 index 0000000..50fd66b --- /dev/null +++ b/evidence/dependency-scan-summary.json @@ -0,0 +1,153 @@ +{ + "dependency-scan-initial": { + "config": { + "protocol_version": "v1.0.0", + "scanner_name": "govulncheck", + "scanner_version": "v1.10.0", + "db": "https://vuln.go.dev", + "db_last_modified": "2026-11-24T15:56:00Z", + "go_version": "go1.27.4", + "scan_level": "symbol", + "scan_mode": "source" + }, + "findings": 423, + "called_advisory_count": 24, + "called_advisories": [ + { + "id": "GO-2023-1572", + "summary": "Denial of service via crafted TIFF image in golang.org/x/image/tiff", + "url": "https://pkg.go.dev/vuln/GO-2023-1572" + }, + { + "id": "GO-2023-1989", + "summary": "Excessive resource consumption in golang.org/x/image/tiff", + "url": "https://pkg.go.dev/vuln/GO-2023-1989" + }, + { + "id": "GO-2023-1990", + "summary": "Excessive CPU consumption when decoding 0-height images in golang.org/x/image/tiff", + "url": "https://pkg.go.dev/vuln/GO-2023-1990" + }, + { + "id": "GO-2024-2937", + "summary": "Panic when parsing invalid palette-color images in golang.org/x/image", + "url": "https://pkg.go.dev/vuln/GO-2024-2937" + }, + { + "id": "GO-2026-4394", + "summary": "OpenTelemetry Go SDK Vulnerable to Arbitrary Code Execution via PATH Hijacking in go.opentelemetry.io/otel/sdk", + "url": "https://pkg.go.dev/vuln/GO-2026-4394" + }, + { + "id": "GO-2026-4815", + "summary": "OOM from malicious IFD offset in golang.org/x/image/tiff", + "url": "https://pkg.go.dev/vuln/GO-2026-4815" + }, + { + "id": "GO-2026-4985", + "summary": "Oversized OTLP HTTP response bodies can cause memory exhaustion in go.opentelemetry.io/otel/exporters/otlp", + "url": "https://pkg.go.dev/vuln/GO-2026-4985" + }, + { + "id": "GO-2026-5004", + "summary": "SQL Injection via placeholder confusion with dollar quoted string literals in github.com/jackc/pgx", + "url": "https://pkg.go.dev/vuln/GO-2026-5004" + }, + { + "id": "GO-2026-5031", + "summary": "Panic when reading out of bound palette index in golang.org/x/image/bmp", + "url": "https://pkg.go.dev/vuln/GO-2026-5031" + }, + { + "id": "GO-2026-5032", + "summary": "Excessive resource consumption in PackBits decompression in golang.org/x/image/tiff", + "url": "https://pkg.go.dev/vuln/GO-2026-5032" + }, + { + "id": "GO-2026-5062", + "summary": "Lack of limit on tile sizes in x/image/tiff in golang.org/x/image", + "url": "https://pkg.go.dev/vuln/GO-2026-5062" + }, + { + "id": "GO-2026-5066", + "summary": "Panic decoding image with out-of-bounds strip offset in x/image/tiff in golang.org/x/image", + "url": "https://pkg.go.dev/vuln/GO-2026-5066" + }, + { + "id": "GO-2026-5506", + "summary": "OpenTelemetry-Go: Multi-value baggage header extraction causes excessive allocations in go.opentelemetry.io/otel", + "url": "https://pkg.go.dev/vuln/GO-2026-5506" + }, + { + "id": "GO-2026-5970", + "summary": "Infinite loop on invalid input in golang.org/x/text", + "url": "https://pkg.go.dev/vuln/GO-2026-5970" + }, + { + "id": "GO-2026-6061", + "summary": "Vulnerabilities in the xDS RBAC authorization engine and the HTTP/2 transport server implementation in google.golang.org/grpc", + "url": "https://pkg.go.dev/vuln/GO-2026-6061" + }, + { + "id": "GO-2026-6348", + "summary": "Heap Memory Exhaustion (OOM) via HTTP/2 DATA Frame Fragmentation in google.golang.org/grpc", + "url": "https://pkg.go.dev/vuln/GO-2026-6348" + }, + { + "id": "GO-2026-6505", + "summary": "OpenTelemetry-Go: Exporter config logging may leak endpoint URLs in info logs in go.opentelemetry.io/otel/exporters/otlp/otlptrace", + "url": "https://pkg.go.dev/vuln/GO-2026-6505" + }, + { + "id": "GO-2026-6603", + "summary": "HTTP/2 server memory exhaustion due to Trailer headers in net/http", + "url": "https://pkg.go.dev/vuln/GO-2026-6603" + }, + { + "id": "GO-2026-6611", + "summary": "Excessive CPU consumption from repeated initial window changes in net/http", + "url": "https://pkg.go.dev/vuln/GO-2026-6611" + }, + { + "id": "GO-2026-6612", + "summary": "Double flow control refund on HTTP/2 server streams in net/http", + "url": "https://pkg.go.dev/vuln/GO-2026-6612" + }, + { + "id": "GO-2026-6615", + "summary": "OpenTelemetry-Go: BatchProcessor can busy-spin when export buffer is full in go.opentelemetry.io/otel/sdk/log", + "url": "https://pkg.go.dev/vuln/GO-2026-6615" + }, + { + "id": "GO-2026-6617", + "summary": "HTTP/2 server crash due to HPACK encoder race in net/http", + "url": "https://pkg.go.dev/vuln/GO-2026-6617" + }, + { + "id": "GO-2026-6629", + "summary": "Panic parsing crafted input in x/text/secure/precis in golang.org/x/text", + "url": "https://pkg.go.dev/vuln/GO-2026-6629" + }, + { + "id": "GO-2026-6974", + "summary": "AttributeValueLengthLimit bypass via U+FFFD runes in go.opentelemetry.io/otel/sdk", + "url": "https://pkg.go.dev/vuln/GO-2026-6974" + } + ] + }, + "dependency-scan": { + "config": { + "protocol_version": "v1.0.0", + "scanner_name": "govulncheck", + "scanner_version": "v1.10.0", + "db": "https://vuln.go.dev", + "db_last_modified": "2026-11-24T15:56:00Z", + "go_version": "go1.27.4", + "scan_level": "symbol", + "scan_mode": "source" + }, + "findings": 0, + "called_advisory_count": 0, + "called_advisories": [] + } +} diff --git a/evidence/dependency-scan.json.gz b/evidence/dependency-scan.json.gz new file mode 100644 index 0000000..d05f861 Binary files /dev/null and b/evidence/dependency-scan.json.gz differ diff --git a/evidence/dependency-update.txt b/evidence/dependency-update.txt new file mode 100644 index 0000000..fe5cc0b --- /dev/null +++ b/evidence/dependency-update.txt @@ -0,0 +1,74 @@ +go: downloading golang.org/x/net v0.63.0 +go: downloading google.golang.org/protobuf v1.36.12 +go: downloading go.opentelemetry.io/proto/otlp v1.11.0 +go: downloading github.com/cenkalti/backoff/v5 v5.0.3 +go: downloading go.opentelemetry.io/otel/log v1.47.0 +go: downloading github.com/go-logr/logr v1.4.4 +go: downloading go.opentelemetry.io/otel/metric v1.47.0 +go: downloading go.opentelemetry.io/otel/trace v1.47.0 +go: downloading go.opentelemetry.io/auto/sdk v1.2.1 +go: downloading go.opentelemetry.io/otel/sdk/metric v1.47.0 +go: downloading google.golang.org/grpc v1.83.2 +go: downloading golang.org/x/text v0.44.0 +go: downloading github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 +go: downloading golang.org/x/sys v0.50.0 +go: downloading google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc +go: downloading google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc +go: downloading github.com/stretchr/testify v1.12.1 +go: downloading go.opentelemetry.io/otel/sdk/log/logtest v0.23.0 +go: upgraded github.com/cenkalti/backoff/v5 v5.0.2 => v5.0.3 +go: upgraded github.com/go-logr/logr v1.4.2 => v1.4.4 +go: upgraded github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 => v2.30.0 +go: upgraded github.com/jackc/pgx/v5 v5.7.6 => v5.9.2 +go: upgraded github.com/klauspost/compress v1.18.0 => v1.20.2 +go: upgraded go.opentelemetry.io/auto/sdk v1.1.0 => v1.2.1 +go: upgraded go.opentelemetry.io/otel v1.36.0 => v1.47.0 +go: upgraded go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.12.2 => v0.23.0 +go: upgraded go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.36.0 => v1.47.0 +go: upgraded go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.36.0 => v1.47.0 +go: upgraded go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.36.0 => v1.47.0 +go: upgraded go.opentelemetry.io/otel/log v0.12.2 => v1.47.0 +go: upgraded go.opentelemetry.io/otel/metric v1.36.0 => v1.47.0 +go: upgraded go.opentelemetry.io/otel/sdk v1.36.0 => v1.47.0 +go: upgraded go.opentelemetry.io/otel/sdk/log v0.12.2 => v1.47.0 +go: upgraded go.opentelemetry.io/otel/sdk/metric v1.36.0 => v1.47.0 +go: upgraded go.opentelemetry.io/otel/trace v1.36.0 => v1.47.0 +go: upgraded go.opentelemetry.io/proto/otlp v1.6.0 => v1.11.0 +go: upgraded golang.org/x/crypto v0.41.0 => v0.59.0 +go: upgraded golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 => v0.45.0 +go: upgraded golang.org/x/net v0.42.0 => v0.63.0 +go: upgraded golang.org/x/sync v0.16.0 => v0.25.0 +go: upgraded golang.org/x/sys v0.35.0 => v0.50.0 +go: upgraded golang.org/x/text v0.28.0 => v0.44.0 +go: upgraded google.golang.org/genproto/googleapis/api v0.0.0-20250519155744-55703ea1f237 => v0.0.0-20260928230214-8a89bd6388cc +go: upgraded google.golang.org/genproto/googleapis/rpc v0.0.0-20250519155744-55703ea1f237 => v0.0.0-20260928230214-8a89bd6388cc +go: upgraded google.golang.org/grpc v1.72.1 => v1.83.2 +go: upgraded google.golang.org/protobuf v1.36.6 => v1.36.12 +go: downloading github.com/google/go-cmp v0.7.0 +go: downloading go.opentelemetry.io/otel/metric/x v0.69.0 +go: downloading go.uber.org/goleak v1.3.0 +go: downloading github.com/golang/protobuf v1.5.4 +go: downloading github.com/bsm/ginkgo/v2 v2.12.0 +go: downloading github.com/bsm/gomega v1.27.10 +go: downloading gonum.org/v1/gonum v0.17.0 +go: downloading go.yaml.in/yaml/v3 v3.0.5 +# go.opentelemetry.io/contrib/bridges/otelslog +/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/handler.go:347:37: undefined: log.KeyValue +/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/handler.go:380:13: undefined: log.KeyValue +/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/handler.go:404:41: undefined: log.KeyValue +/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/handler.go:452:32: undefined: log.Value +/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:20:30: undefined: log.Value +/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:24:14: undefined: log.BoolValue +/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:26:14: undefined: log.StringValue +/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:28:14: undefined: log.Int64Value +/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:30:14: undefined: log.Int64Value +/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:118:37: undefined: log.Value +/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:30:14: too many errors +? mtusi/messenger/internal/security [no test files] +FAIL mtusi/messenger/cmd/server [build failed] +FAIL +go: downloading go.opentelemetry.io/contrib v1.47.0 +go: downloading go.opentelemetry.io/contrib/bridges/otelslog v0.21.0 +go: upgraded go.opentelemetry.io/contrib/bridges/otelslog v0.11.0 => v0.21.0 +? mtusi/messenger/internal/security [no test files] +? mtusi/messenger/cmd/server [no test files] diff --git a/evidence/dependency-versions.txt b/evidence/dependency-versions.txt new file mode 100644 index 0000000..9d61d4a --- /dev/null +++ b/evidence/dependency-versions.txt @@ -0,0 +1,118 @@ +mtusi/messenger +cel.dev/expr v0.25.2 +cloud.google.com/go/auth v0.18.2 +cloud.google.com/go/compute/metadata v0.9.0 +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 +github.com/apapsch/go-jsonmerge/v2 v2.0.0 +github.com/bsm/ginkgo/v2 v2.12.0 +github.com/bsm/gomega v1.27.10 +github.com/cenkalti/backoff/v5 v5.0.3 +github.com/cespare/xxhash/v2 v2.3.0 +github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 +github.com/davecgh/go-spew v1.1.1 +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f +github.com/disintegration/imaging v1.6.2 +github.com/dustin/go-humanize v1.0.1 +github.com/envoyproxy/go-control-plane v0.14.0 +github.com/envoyproxy/go-control-plane/envoy v1.37.0 +github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 +github.com/envoyproxy/protoc-gen-validate v1.3.3 +github.com/felixge/httpsnoop v1.1.0 +github.com/go-ini/ini v1.67.0 +github.com/go-jose/go-jose/v4 v4.1.4 +github.com/go-logr/logr v1.4.4 +github.com/go-logr/stdr v1.2.2 +github.com/go-openapi/analysis v0.25.5 +github.com/go-openapi/errors v0.22.8 +github.com/go-openapi/jsonpointer v1.0.0 +github.com/go-openapi/jsonreference v1.0.0 +github.com/go-openapi/loads v0.25.0 +github.com/go-openapi/runtime v0.33.0 +github.com/go-openapi/runtime/server-middleware v0.30.0 +github.com/go-openapi/spec v0.22.9 +github.com/go-openapi/strfmt v0.27.0 +github.com/go-openapi/swag v0.28.0 +github.com/go-openapi/swag/cmdutils v0.28.0 +github.com/go-openapi/swag/conv v0.28.0 +github.com/go-openapi/swag/fileutils v0.28.0 +github.com/go-openapi/swag/jsonutils v0.28.0 +github.com/go-openapi/swag/loading v0.28.0 +github.com/go-openapi/swag/mangling v0.28.0 +github.com/go-openapi/swag/netutils v0.28.0 +github.com/go-openapi/swag/pools v0.28.0 +github.com/go-openapi/swag/stringutils v0.28.0 +github.com/go-openapi/swag/typeutils v0.28.0 +github.com/go-openapi/swag/yamlutils v0.28.0 +github.com/go-openapi/validate v0.26.1 +github.com/go-viper/mapstructure/v2 v2.5.0 +github.com/goccy/go-json v0.10.5 +github.com/golang/glog v1.2.5 +github.com/golang/protobuf v1.5.4 +github.com/google/go-cmp v0.7.0 +github.com/google/s2a-go v0.1.9 +github.com/google/uuid v1.6.0 +github.com/googleapis/enterprise-certificate-proxy v0.3.11 +github.com/googleapis/gax-go/v2 v2.17.0 +github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 +github.com/jackc/pgpassfile v1.0.0 +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 +github.com/jackc/pgx/v5 v5.9.2 +github.com/jackc/puddle/v2 v2.2.2 +github.com/klauspost/compress v1.20.2 +github.com/klauspost/cpuid/v2 v2.2.11 +github.com/kr/pretty v0.3.1 +github.com/minio/crc64nvme v1.0.2 +github.com/minio/md5-simd v1.1.2 +github.com/minio/minio-go/v7 v7.0.95 +github.com/oapi-codegen/runtime v1.6.0 +github.com/oklog/ulid/v2 v2.1.1 +github.com/philhofer/fwd v1.2.0 +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 +github.com/pmezard/go-difflib v1.0.0 +github.com/redis/go-redis/v9 v9.12.1 +github.com/rogpeppe/fastuuid v1.2.0 +github.com/rogpeppe/go-internal v1.14.1 +github.com/rs/xid v1.6.0 +github.com/spiffe/go-spiffe/v2 v2.7.0 +github.com/stretchr/objx v0.1.0 +github.com/stretchr/testify v1.12.1 +github.com/tinylib/msgp v1.3.0 +go.opentelemetry.io/auto/sdk v1.2.1 +go.opentelemetry.io/contrib/bridges/otelslog v0.21.0 +go.opentelemetry.io/contrib/detectors/gcp v1.44.0 +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0 +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 +go.opentelemetry.io/otel v1.47.0 +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0 +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 +go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.45.0 +go.opentelemetry.io/otel/log v1.47.0 +go.opentelemetry.io/otel/metric v1.47.0 +go.opentelemetry.io/otel/metric/x v0.69.0 +go.opentelemetry.io/otel/sdk v1.47.0 +go.opentelemetry.io/otel/sdk/log v1.47.0 +go.opentelemetry.io/otel/sdk/log/logtest v0.23.0 +go.opentelemetry.io/otel/sdk/metric v1.47.0 +go.opentelemetry.io/otel/trace v1.47.0 +go.opentelemetry.io/proto/otlp v1.11.0 +go.uber.org/goleak v1.3.0 +go.yaml.in/yaml/v3 v3.0.5 +golang.org/x/crypto v0.59.0 +golang.org/x/image v0.45.0 +golang.org/x/mod v0.42.0 +golang.org/x/net v0.63.0 +golang.org/x/oauth2 v0.36.0 +golang.org/x/sync v0.25.0 +golang.org/x/sys v0.50.0 +golang.org/x/term v0.48.0 +golang.org/x/text v0.44.0 +golang.org/x/tools v0.52.0 +gonum.org/v1/gonum v0.17.0 +google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc +google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc +google.golang.org/grpc v1.83.2 +google.golang.org/protobuf v1.36.12 +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c +gopkg.in/yaml.v3 v3.0.1 diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 0000000..d97fa85 --- /dev/null +++ b/evidence/failover.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "https://localhost:8443" --ca-file "/Users/glebkraykin/Projects/highload-apps-labs/lab7/certs/ca.crt" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 110, "failed_attempts": 1, "first_recovery_seconds": 1.149} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/hardening.json b/evidence/hardening.json new file mode 100644 index 0000000..9af2bd1 --- /dev/null +++ b/evidence/hardening.json @@ -0,0 +1,505 @@ +{ + "runtime": [ + { + "service": "api", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 805306368, + "nano_cpus_limit": 1000000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:19:37.993962054Z", + "published_ports": {} + }, + { + "service": "api", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 805306368, + "nano_cpus_limit": 1000000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:10:41.942116375Z", + "published_ports": {} + }, + { + "service": "broker", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 134217728, + "nano_cpus_limit": 500000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:10:38.562146138Z", + "published_ports": {} + }, + { + "service": "broker-store", + "user": "999:1000", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 268435456, + "nano_cpus_limit": 500000000, + "image_id": "sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773", + "started_at": "2026-12-02T14:10:38.722964263Z", + "published_ports": {} + }, + { + "service": "cache", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 134217728, + "nano_cpus_limit": 500000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:10:38.577258679Z", + "published_ports": {} + }, + { + "service": "cache-store", + "user": "999:1000", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 268435456, + "nano_cpus_limit": 500000000, + "image_id": "sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773", + "started_at": "2026-12-02T14:10:38.753695763Z", + "published_ports": {} + }, + { + "service": "collector", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 134217728, + "nano_cpus_limit": 500000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:10:38.574985221Z", + "published_ports": {} + }, + { + "service": "collector-store", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 268435456, + "nano_cpus_limit": 500000000, + "image_id": "sha256:1ab0baba0ee3695d823c46653d8a6e8894896e668ce8bd7ebe002e948d827bc7", + "started_at": "2026-12-02T14:10:38.874202929Z", + "published_ports": {} + }, + { + "service": "dispatcher", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 134217728, + "nano_cpus_limit": 250000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:10:41.933912166Z", + "published_ports": {} + }, + { + "service": "grafana", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 134217728, + "nano_cpus_limit": 500000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:10:38.559359388Z", + "published_ports": { + "3000/tcp": [ + { + "HostIp": "127.0.0.1", + "HostPort": "3007" + } + ] + } + }, + { + "service": "grafana-store", + "user": "472", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 268435456, + "nano_cpus_limit": 500000000, + "image_id": "sha256:b5b59bfc7561634c2d7b136c4543d702ebcc94a3da477f21ff26f89ffd4214fa", + "started_at": "2026-12-02T14:10:38.755523763Z", + "published_ports": {} + }, + { + "service": "housekeeping", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 134217728, + "nano_cpus_limit": 250000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:10:41.941801375Z", + "published_ports": {} + }, + { + "service": "lb", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 134217728, + "nano_cpus_limit": 1000000000, + "image_id": "sha256:3a819392f5a6af2a9203d1c63ff0feba74f0c940623a558511be06d7d85e361c", + "started_at": "2026-12-02T14:10:42.1189875Z", + "published_ports": { + "8443/tcp": [ + { + "HostIp": "127.0.0.1", + "HostPort": "8443" + } + ] + } + }, + { + "service": "loki", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 134217728, + "nano_cpus_limit": 500000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:10:38.581135971Z", + "published_ports": {} + }, + { + "service": "loki-store", + "user": "10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 268435456, + "nano_cpus_limit": 500000000, + "image_id": "sha256:a74594532eec4cc313401beedc4dd2708c43674c032084b1aeb87c14a5be1745", + "started_at": "2026-12-02T14:10:38.840854804Z", + "published_ports": {} + }, + { + "service": "openbao", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 268435456, + "nano_cpus_limit": 500000000, + "image_id": "sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9", + "started_at": "2026-12-02T14:10:39.320626388Z", + "published_ports": { + "8200/tcp": [ + { + "HostIp": "127.0.0.1", + "HostPort": "8207" + } + ] + } + }, + { + "service": "postgres", + "user": "", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": [ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FOWNER", + "CAP_SETGID", + "CAP_SETUID" + ], + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 536870912, + "nano_cpus_limit": 2000000000, + "image_id": "sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94", + "started_at": "2026-12-02T14:10:38.582143221Z", + "published_ports": {} + }, + { + "service": "prometheus", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 134217728, + "nano_cpus_limit": 500000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:10:38.491951637Z", + "published_ports": {} + }, + { + "service": "prometheus-store", + "user": "nobody", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 268435456, + "nano_cpus_limit": 500000000, + "image_id": "sha256:9abc6cf6aea7710d163dbb28d8eeb7dc5baef01e38fa4cd146a406dd9f07f70d", + "started_at": "2026-12-02T14:10:38.673212388Z", + "published_ports": {} + }, + { + "service": "s3", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 134217728, + "nano_cpus_limit": 500000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:10:38.572567096Z", + "published_ports": {} + }, + { + "service": "s3-store", + "user": "", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 536870912, + "nano_cpus_limit": 1000000000, + "image_id": "sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e", + "started_at": "2026-12-02T14:10:38.783305721Z", + "published_ports": {} + }, + { + "service": "tempo", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 134217728, + "nano_cpus_limit": 500000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:10:38.500782637Z", + "published_ports": {} + }, + { + "service": "tempo-store", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 268435456, + "nano_cpus_limit": 500000000, + "image_id": "sha256:3cbb1b4eae79b158d25006d88abadb1f87ef98f8a902cd54c3bdffff78ea6cda", + "started_at": "2026-12-02T14:10:38.655961679Z", + "published_ports": {} + }, + { + "service": "worker", + "user": "10001:10001", + "read_only": true, + "drop_capabilities": [ + "ALL" + ], + "add_capabilities": null, + "security_options": [ + "no-new-privileges:true" + ], + "memory_limit_bytes": 1073741824, + "nano_cpus_limit": 1000000000, + "image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245", + "started_at": "2026-12-02T14:19:31.736994051Z", + "published_ports": {} + } + ], + "no_native_bypass": [ + { + "service": "api", + "native_port": 8081, + "external_namespace_connection_denied": true + }, + { + "service": "broker", + "native_port": 6380, + "external_namespace_connection_denied": true + }, + { + "service": "cache", + "native_port": 6380, + "external_namespace_connection_denied": true + }, + { + "service": "s3", + "native_port": 9001, + "external_namespace_connection_denied": true + }, + { + "service": "s3", + "native_port": 9002, + "external_namespace_connection_denied": true + }, + { + "service": "collector", + "native_port": 4319, + "external_namespace_connection_denied": true + }, + { + "service": "collector", + "native_port": 8890, + "external_namespace_connection_denied": true + }, + { + "service": "prometheus", + "native_port": 9091, + "external_namespace_connection_denied": true + }, + { + "service": "loki", + "native_port": 3101, + "external_namespace_connection_denied": true + }, + { + "service": "tempo", + "native_port": 3201, + "external_namespace_connection_denied": true + }, + { + "service": "grafana", + "native_port": 3001, + "external_namespace_connection_denied": true + } + ], + "worker_filesystem": { + "rootfs_write": "denied", + "operator_key": "denied", + "other_identity": "denied" + }, + "worker_effective_caps_zero": true, + "worker_no_new_privileges": true, + "known_private_values_absent_from_config_env_and_sampled_logs": true, + "scope": "runtime containers only; verify-profile compiler/operator tools not persistent runtime; last500 app/collector log lines sampled, not proof of all future logs" +} diff --git a/evidence/hardening.txt b/evidence/hardening.txt new file mode 100644 index 0000000..5e72bd6 --- /dev/null +++ b/evidence/hardening.txt @@ -0,0 +1 @@ +PASS: actual non-root/capabilities/read-only/ports, closed native hops, scoped worker mounts and sampled private-value scan diff --git a/evidence/load-resources.json b/evidence/load-resources.json new file mode 100644 index 0000000..318c2b0 --- /dev/null +++ b/evidence/load-resources.json @@ -0,0 +1,314 @@ +{ + "requested_duration_seconds": 15, + "concurrency": 4, + "warmup_seconds": 0, + "before": { + "users": 35, + "chats": 13, + "messages": 609, + "attachments": 16 + }, + "after": { + "users": 38, + "chats": 14, + "messages": 2995, + "attachments": 16 + }, + "resource_observations": [ + { + "elapsed_seconds": 1.771, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "42.59%", + "Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8", + "ID": "184f26c3f953", + "MemPerc": "21.90%", + "MemUsage": "168.2MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-1", + "NetIO": "1.15MB / 1.62MB", + "PIDs": "16" + }, + { + "BlockIO": "0B / 0B", + "CPUPerc": "41.75%", + "Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec", + "ID": "83ebe4343681", + "MemPerc": "18.43%", + "MemUsage": "141.6MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-2", + "NetIO": "252kB / 323kB", + "PIDs": "15" + }, + { + "BlockIO": "3.23MB / 0B", + "CPUPerc": "1.07%", + "Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a", + "ID": "7703854ae2b9", + "MemPerc": "27.97%", + "MemUsage": "71.61MiB / 256MiB", + "Name": "mtusi-lab7-kraykin-collector-store-1", + "NetIO": "13.7MB / 8.39MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 0B", + "CPUPerc": "0.03%", + "Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4", + "ID": "71cbb9cee6bb", + "MemPerc": "1.70%", + "MemUsage": "17.4MiB / 1GiB", + "Name": "mtusi-lab7-kraykin-worker-1", + "NetIO": "1.65MB / 2.39MB", + "PIDs": "17" + } + ] + }, + { + "elapsed_seconds": 4.804, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "15.93%", + "Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8", + "ID": "184f26c3f953", + "MemPerc": "22.06%", + "MemUsage": "169.4MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-1", + "NetIO": "2.81MB / 3.99MB", + "PIDs": "16" + }, + { + "BlockIO": "0B / 0B", + "CPUPerc": "29.32%", + "Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec", + "ID": "83ebe4343681", + "MemPerc": "2.75%", + "MemUsage": "21.13MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-2", + "NetIO": "3.07MB / 4.39MB", + "PIDs": "15" + }, + { + "BlockIO": "3.23MB / 0B", + "CPUPerc": "2.66%", + "Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a", + "ID": "7703854ae2b9", + "MemPerc": "27.98%", + "MemUsage": "71.63MiB / 256MiB", + "Name": "mtusi-lab7-kraykin-collector-store-1", + "NetIO": "14.8MB / 8.75MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 0B", + "CPUPerc": "0.52%", + "Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4", + "ID": "71cbb9cee6bb", + "MemPerc": "1.70%", + "MemUsage": "17.43MiB / 1GiB", + "Name": "mtusi-lab7-kraykin-worker-1", + "NetIO": "1.66MB / 2.4MB", + "PIDs": "17" + } + ] + }, + { + "elapsed_seconds": 7.836, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "24.06%", + "Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8", + "ID": "184f26c3f953", + "MemPerc": "5.34%", + "MemUsage": "41.02MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-1", + "NetIO": "6.07MB / 8.76MB", + "PIDs": "16" + }, + { + "BlockIO": "193kB / 0B", + "CPUPerc": "3.34%", + "Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec", + "ID": "83ebe4343681", + "MemPerc": "2.66%", + "MemUsage": "20.4MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-2", + "NetIO": "5.25MB / 7.57MB", + "PIDs": "16" + }, + { + "BlockIO": "3.23MB / 0B", + "CPUPerc": "1.03%", + "Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a", + "ID": "7703854ae2b9", + "MemPerc": "28.68%", + "MemUsage": "73.43MiB / 256MiB", + "Name": "mtusi-lab7-kraykin-collector-store-1", + "NetIO": "17MB / 9.52MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 0B", + "CPUPerc": "0.38%", + "Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4", + "ID": "71cbb9cee6bb", + "MemPerc": "1.71%", + "MemUsage": "17.47MiB / 1GiB", + "Name": "mtusi-lab7-kraykin-worker-1", + "NetIO": "1.66MB / 2.4MB", + "PIDs": "17" + } + ] + }, + { + "elapsed_seconds": 10.883, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "3.61%", + "Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8", + "ID": "184f26c3f953", + "MemPerc": "5.25%", + "MemUsage": "40.3MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-1", + "NetIO": "6.41MB / 9.28MB", + "PIDs": "16" + }, + { + "BlockIO": "193kB / 0B", + "CPUPerc": "2.80%", + "Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec", + "ID": "83ebe4343681", + "MemPerc": "2.62%", + "MemUsage": "20.16MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-2", + "NetIO": "5.42MB / 7.83MB", + "PIDs": "16" + }, + { + "BlockIO": "3.23MB / 0B", + "CPUPerc": "2.86%", + "Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a", + "ID": "7703854ae2b9", + "MemPerc": "27.22%", + "MemUsage": "69.68MiB / 256MiB", + "Name": "mtusi-lab7-kraykin-collector-store-1", + "NetIO": "17.2MB / 9.6MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 0B", + "CPUPerc": "0.57%", + "Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4", + "ID": "71cbb9cee6bb", + "MemPerc": "1.71%", + "MemUsage": "17.51MiB / 1GiB", + "Name": "mtusi-lab7-kraykin-worker-1", + "NetIO": "1.67MB / 2.41MB", + "PIDs": "17" + } + ] + }, + { + "elapsed_seconds": 13.927, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "2.66%", + "Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8", + "ID": "184f26c3f953", + "MemPerc": "5.25%", + "MemUsage": "40.29MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-1", + "NetIO": "6.57MB / 9.51MB", + "PIDs": "16" + }, + { + "BlockIO": "193kB / 0B", + "CPUPerc": "4.57%", + "Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec", + "ID": "83ebe4343681", + "MemPerc": "2.86%", + "MemUsage": "21.99MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-2", + "NetIO": "5.76MB / 8.34MB", + "PIDs": "16" + }, + { + "BlockIO": "3.23MB / 0B", + "CPUPerc": "0.88%", + "Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a", + "ID": "7703854ae2b9", + "MemPerc": "27.64%", + "MemUsage": "70.75MiB / 256MiB", + "Name": "mtusi-lab7-kraykin-collector-store-1", + "NetIO": "17.4MB / 9.68MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 0B", + "CPUPerc": "0.31%", + "Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4", + "ID": "71cbb9cee6bb", + "MemPerc": "1.74%", + "MemUsage": "17.81MiB / 1GiB", + "Name": "mtusi-lab7-kraykin-worker-1", + "NetIO": "1.67MB / 2.42MB", + "PIDs": "17" + } + ] + }, + { + "elapsed_seconds": 16.977, + "containers": [ + { + "BlockIO": "0B / 0B", + "CPUPerc": "3.25%", + "Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8", + "ID": "184f26c3f953", + "MemPerc": "5.25%", + "MemUsage": "40.3MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-1", + "NetIO": "6.84MB / 9.91MB", + "PIDs": "16" + }, + { + "BlockIO": "193kB / 0B", + "CPUPerc": "4.92%", + "Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec", + "ID": "83ebe4343681", + "MemPerc": "2.88%", + "MemUsage": "22.09MiB / 768MiB", + "Name": "mtusi-lab7-kraykin-api-2", + "NetIO": "6.11MB / 8.83MB", + "PIDs": "16" + }, + { + "BlockIO": "3.23MB / 0B", + "CPUPerc": "1.40%", + "Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a", + "ID": "7703854ae2b9", + "MemPerc": "27.64%", + "MemUsage": "70.75MiB / 256MiB", + "Name": "mtusi-lab7-kraykin-collector-store-1", + "NetIO": "17.6MB / 9.77MB", + "PIDs": "19" + }, + { + "BlockIO": "0B / 0B", + "CPUPerc": "0.33%", + "Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4", + "ID": "71cbb9cee6bb", + "MemPerc": "1.72%", + "MemUsage": "17.57MiB / 1GiB", + "Name": "mtusi-lab7-kraykin-worker-1", + "NetIO": "1.68MB / 2.43MB", + "PIDs": "17" + } + ] + } + ], + "limits": "closed-loop/coordinated omission, success-only latency percentiles, shared VM, growing dataset; no capacity or TLS off/on comparison" +} diff --git a/evidence/load.json b/evidence/load.json new file mode 100644 index 0000000..325b229 --- /dev/null +++ b/evidence/load.json @@ -0,0 +1,17 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 15.0, + "elapsed_seconds": 15.01, + "concurrency": 4, + "successful_requests": 2386, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 158.96, + "successful_latency_ms": { + "p50": 8.173, + "p95": 129.663, + "p99": 196.474 + }, + "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 0000000..c381b7b --- /dev/null +++ b/evidence/load.txt @@ -0,0 +1,18 @@ +{ + "lab": 7, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 15.0, + "elapsed_seconds": 15.01, + "concurrency": 4, + "successful_requests": 2386, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 158.96, + "successful_latency_ms": { + "p50": 8.173, + "p95": 129.663, + "p99": 196.474 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} +MEASURED: verified HTTPS workload, errors, percentiles, CPU/RAM and dataset counts diff --git a/evidence/openapi.txt b/evidence/openapi.txt new file mode 100644 index 0000000..365e77e --- /dev/null +++ b/evidence/openapi.txt @@ -0,0 +1,4 @@ +/private/tmp/highload7-verify/bin/python scripts/validate_openapi.py +/private/tmp/highload7-verify/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020 + warnings.warn( +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. diff --git a/evidence/openbao-policy.json b/evidence/openbao-policy.json new file mode 100644 index 0000000..0cd85dc --- /dev/null +++ b/evidence/openbao-policy.json @@ -0,0 +1,46 @@ +[ + { + "role": "api", + "ttl_seconds": 60, + "own_read": true, + "denied_paths": [ + "kv/data/worker", + "sys/policies/acl/escalation", + "sys/raw/core" + ], + "revoked_token_denied": true + }, + { + "role": "worker", + "ttl_seconds": 60, + "own_read": true, + "denied_paths": [ + "kv/data/api", + "sys/policies/acl/escalation", + "sys/raw/core" + ], + "revoked_token_denied": true + }, + { + "role": "dispatcher", + "ttl_seconds": 60, + "own_read": true, + "denied_paths": [ + "kv/data/api", + "sys/policies/acl/escalation", + "sys/raw/core" + ], + "revoked_token_denied": true + }, + { + "role": "housekeeping", + "ttl_seconds": 60, + "own_read": true, + "denied_paths": [ + "kv/data/api", + "sys/policies/acl/escalation", + "sys/raw/core" + ], + "revoked_token_denied": true + } +] diff --git a/evidence/operations.json b/evidence/operations.json new file mode 100644 index 0000000..5ad52e3 --- /dev/null +++ b/evidence/operations.json @@ -0,0 +1,30 @@ +{ + "failures": [ + { + "successful_writes": 148, + "errors": 1, + "successful_rps": 17.529176246121644, + "first_recovery_seconds": 1.118, + "action_seconds": 0.258, + "instances": [ + "4e1905fc-f951-4020-b910-d8ef3ccfdeea", + "7c6edd04-09c4-48cc-993d-87981c6277ab" + ], + "confirmed_preserved": true, + "stopped_alias": "7c6edd04-09c4-48cc-993d-87981c6277ab" + }, + { + "successful_writes": 143, + "errors": 2, + "successful_rps": 16.77245908330838, + "first_recovery_seconds": 0.306, + "action_seconds": 0.29, + "instances": [ + "032ca595-80b4-48ed-b90d-2c36098714e5", + "4e1905fc-f951-4020-b910-d8ef3ccfdeea" + ], + "confirmed_preserved": true, + "stopped_alias": "4e1905fc-f951-4020-b910-d8ef3ccfdeea" + } + ] +} diff --git a/evidence/operations.txt b/evidence/operations.txt new file mode 100644 index 0000000..e76b057 --- /dev/null +++ b/evidence/operations.txt @@ -0,0 +1 @@ +PASS: both API replicas stopped sequentially through verified HTTPS; confirmed writes preserved diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 0000000..99d1931 --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "https://localhost:8443" --ca-file "/Users/glebkraykin/Projects/highload-apps-labs/lab7/certs/ca.crt" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/public-tls.txt b/evidence/public-tls.txt new file mode 100644 index 0000000..29e5172 --- /dev/null +++ b/evidence/public-tls.txt @@ -0,0 +1,2 @@ +python3 tests/security.py --base-url "https://localhost:8443" --ca-file "/Users/glebkraykin/Projects/highload-apps-labs/lab7/certs/ca.crt" +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. diff --git a/evidence/race.txt b/evidence/race.txt new file mode 100644 index 0000000..055ea73 --- /dev/null +++ b/evidence/race.txt @@ -0,0 +1,21 @@ +? mtusi/messenger/cmd/server [no test files] +? mtusi/messenger/internal/database [no test files] +=== RUN TestDatabaseConcurrentHTTP + database_test.go:162: 100 confirmed messages from 10 clients through real HTTP and PostgreSQL; race detector enabled +--- PASS: TestDatabaseConcurrentHTTP (1.99s) +=== RUN TestPasswordFullUnicodeRange +--- PASS: TestPasswordFullUnicodeRange (2.23s) +=== RUN TestLegacyArgon2RehashOnHTTPLogin +--- PASS: TestLegacyArgon2RehashOnHTTPLogin (2.35s) +=== RUN TestTransformFailureClassification +--- PASS: TestTransformFailureClassification (0.00s) +=== RUN TestFitFloorNoUpscale +--- PASS: TestFitFloorNoUpscale (0.00s) +=== RUN TestTransformAlphaAndEXIF +--- PASS: TestTransformAlphaAndEXIF (0.22s) +=== RUN TestPNGEXIFAndMalformedIFD +--- PASS: TestPNGEXIFAndMalformedIFD (0.11s) +PASS +ok mtusi/messenger/internal/messenger 7.932s +? mtusi/messenger/internal/security [no test files] +? mtusi/messenger/internal/telemetry [no test files] diff --git a/evidence/restored.txt b/evidence/restored.txt new file mode 100644 index 0000000..e3e371e --- /dev/null +++ b/evidence/restored.txt @@ -0,0 +1,8 @@ + Container mtusi-lab7-kraykin-api-1 Created + Container mtusi-lab7-kraykin-api-2 Running + Container mtusi-lab7-kraykin-api-1 Starting + Container mtusi-lab7-kraykin-api-1 Started + Container mtusi-lab7-kraykin-api-2 Waiting + Container mtusi-lab7-kraykin-api-1 Waiting + Container mtusi-lab7-kraykin-api-2 Healthy + Container mtusi-lab7-kraykin-api-1 Healthy diff --git a/evidence/sealed-expiry.json b/evidence/sealed-expiry.json new file mode 100644 index 0000000..9715413 --- /dev/null +++ b/evidence/sealed-expiry.json @@ -0,0 +1,150 @@ +{ + "expired_correct_identity_leaf": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "sealed_timeline": [ + { + "seconds": 1.42, + "http_status": 200 + }, + { + "seconds": 3.435, + "http_status": 200 + }, + { + "seconds": 5.495, + "http_status": 200 + }, + { + "seconds": 7.532, + "http_status": 200 + }, + { + "seconds": 9.555, + "http_status": 200 + }, + { + "seconds": 11.608, + "http_status": 200 + }, + { + "seconds": 13.635, + "http_status": 200 + }, + { + "seconds": 15.718, + "http_status": 200 + }, + { + "seconds": 17.746, + "http_status": 200 + }, + { + "seconds": 19.83, + "http_status": 200 + }, + { + "seconds": 21.852, + "http_status": 200 + }, + { + "seconds": 23.921, + "http_status": 200 + }, + { + "seconds": 25.991, + "http_status": 200 + }, + { + "seconds": 28.05, + "http_status": 200 + }, + { + "seconds": 30.101, + "http_status": 200 + }, + { + "seconds": 32.167, + "http_status": 200 + }, + { + "seconds": 34.196, + "http_status": 200 + }, + { + "seconds": 36.259, + "http_status": 200 + }, + { + "seconds": 38.281, + "http_status": 200 + }, + { + "seconds": 40.304, + "http_status": 200 + }, + { + "seconds": 42.328, + "http_status": 200 + }, + { + "seconds": 44.362, + "http_status": 200 + }, + { + "seconds": 46.421, + "http_status": 200 + }, + { + "seconds": 48.456, + "http_status": 200 + }, + { + "seconds": 50.491, + "http_status": 200 + }, + { + "seconds": 52.516, + "http_status": 200 + }, + { + "seconds": 54.613, + "http_status": 200 + }, + { + "seconds": 56.638, + "http_status": 200 + }, + { + "seconds": 58.671, + "http_status": 200 + }, + { + "seconds": 60.698, + "http_status": 503 + }, + { + "seconds": 62.766, + "http_status": 503 + }, + { + "seconds": 64.775, + "http_status": 503 + }, + { + "seconds": 66.824, + "http_status": 503 + } + ], + "authorization_ttl_seconds": 60, + "poll_seconds": 5, + "observation_step_seconds": 2, + "restarted_one_api_while_sealed": true, + "restart_had_no_static_secret_fallback": true, + "all_api_unavailable_observed_seconds": 60.698, + "recovery_seconds_after_unseal": 4.324, + "same_user_token_valid": true, + "original_identical": true, + "limits": "successful secret-read authorization cached until60s, refresh attempt timeout<=3s and loop5s; external TLS remains required; local single Bao fails closed after bounded cache" +} diff --git a/evidence/sealed-expiry.txt b/evidence/sealed-expiry.txt new file mode 100644 index 0000000..0333bf9 --- /dev/null +++ b/evidence/sealed-expiry.txt @@ -0,0 +1 @@ +PASS: expired correct-SAN leaf rejected; sealed Bao bounds authorization, restarted API has no fallback, operator unseal restores same session/file diff --git a/evidence/security.txt b/evidence/security.txt new file mode 100644 index 0000000..5b7f460 --- /dev/null +++ b/evidence/security.txt @@ -0,0 +1,4 @@ +PASS: every API replica, broker, Collector and backend trust matrix; real TLS verification failures +PASS: actual scoped OpenBao read/deny, short TTL, token revocation, forbidden identity +PASS: attachment ACL, forged header, cross-chat link, expiry/logout, password/token hashes +PASS: shared rate limit across two replicas with429/Retry-After; measured KDF budget diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 0000000..dd6db15 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/Users/glebkraykin/Projects/highload-apps-labs/lab7/certs/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/startup.txt b/evidence/startup.txt new file mode 100644 index 0000000..a8e8668 --- /dev/null +++ b/evidence/startup.txt @@ -0,0 +1,206 @@ +Operator bootstrap complete; private values hidden; existing identities preserved. +Compose can now delegate builds to bake for better performance. + To do so, set COMPOSE_BAKE=true. +#0 building with "desktop-linux" instance using docker driver + +#1 [api internal] load build definition from Dockerfile +#1 transferring dockerfile: 1.11kB done +#1 DONE 0.0s + +#2 [api internal] load metadata for docker.io/library/alpine:3.24.4 +#2 DONE 0.0s + +#3 [api internal] load metadata for docker.io/library/golang:1.27.4-alpine3.24 +#3 DONE 0.0s + +#4 [api internal] load .dockerignore +#4 transferring context: 196B done +#4 DONE 0.0s + +#5 [api build 1/7] FROM docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 +#5 resolve docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 done +#5 DONE 0.0s + +#6 [api stage-2 1/4] FROM docker.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf +#6 resolve docker.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf done +#6 DONE 0.0s + +#7 [api internal] load build context +#7 transferring context: 9.92kB done +#7 DONE 0.0s + +#8 [api build 2/7] WORKDIR /src +#8 CACHED + +#9 [api build 3/7] COPY go.mod go.sum ./ +#9 CACHED + +#10 [api build 4/7] RUN --mount=type=cache,target=/go/pkg/mod GODEBUG=http2client=0 GOPROXY="https://proxy.golang.org,direct" go mod download +#10 CACHED + +#11 [api build 5/7] COPY cmd/ ./cmd/ +#11 DONE 0.0s + +#12 [api build 6/7] COPY internal/ ./internal/ +#12 DONE 0.0s + +#13 [api build 7/7] RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server +#13 DONE 10.9s + +#14 [api stage-2 2/4] RUN apk add --no-cache libwebp-tools +#14 CACHED + +#15 [api stage-2 3/4] RUN addgroup -g 10001 app && adduser -D -u 10001 -G app app +#15 CACHED + +#16 [api stage-2 4/4] COPY --from=build /out/messenger /usr/local/bin/messenger +#16 DONE 0.1s + +#17 [api] exporting to image +#17 exporting layers +#17 exporting layers 0.6s done +#17 exporting manifest sha256:d38e4cb8b5519627f629121a7d8594bcdf1d12af48551b725a9de6b1e2fa75a5 +#17 exporting manifest sha256:d38e4cb8b5519627f629121a7d8594bcdf1d12af48551b725a9de6b1e2fa75a5 done +#17 exporting config sha256:f7008c0974492ee68462da13a3f1453ee646c42b1e5a2f1dac8553c6867b0ee2 done +#17 exporting attestation manifest sha256:eda01449c2bd6404cf741bf9e9e8925f1985f3ac6f9d39c5398b95ab5a356bcb done +#17 exporting manifest list sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245 done +#17 naming to docker.io/library/mtusi-messenger:lab7 done +#17 unpacking to docker.io/library/mtusi-messenger:lab7 +#17 unpacking to docker.io/library/mtusi-messenger:lab7 0.3s done +#17 DONE 0.9s + +#18 [api] resolving provenance for metadata file +#18 DONE 0.0s + api Built + Container mtusi-lab7-kraykin-tempo-1 Recreate + Container mtusi-lab7-kraykin-storage-init-1 Recreate + Container mtusi-lab7-kraykin-broker-1 Recreate + Container mtusi-lab7-kraykin-prometheus-1 Recreate + Container mtusi-lab7-kraykin-collector-1 Recreate + Container mtusi-lab7-kraykin-grafana-1 Recreate + Container mtusi-lab7-kraykin-loki-1 Recreate + Container mtusi-lab7-kraykin-cache-1 Recreate + Container mtusi-lab7-kraykin-postgres-1 Recreate + Container mtusi-lab7-kraykin-s3-init-1 Stopping + Container mtusi-lab7-kraykin-s3-init-1 Stopped + Container mtusi-lab7-kraykin-s3-1 Recreate + Container mtusi-lab7-kraykin-storage-init-1 Recreated + Container mtusi-lab7-kraykin-openbao-1 Recreate + Container mtusi-lab7-kraykin-prometheus-1 Recreated + Container mtusi-lab7-kraykin-prometheus-store-1 Recreate + Container mtusi-lab7-kraykin-loki-1 Recreated + Container mtusi-lab7-kraykin-loki-store-1 Recreate + Container mtusi-lab7-kraykin-tempo-1 Recreated + Container mtusi-lab7-kraykin-tempo-store-1 Recreate + Container mtusi-lab7-kraykin-s3-1 Recreated + Container mtusi-lab7-kraykin-s3-store-1 Recreate + Container mtusi-lab7-kraykin-cache-1 Recreated + Container mtusi-lab7-kraykin-cache-store-1 Recreate + Container mtusi-lab7-kraykin-grafana-1 Recreated + Container mtusi-lab7-kraykin-grafana-store-1 Recreate + Container mtusi-lab7-kraykin-broker-1 Recreated + Container mtusi-lab7-kraykin-broker-store-1 Recreate + Container mtusi-lab7-kraykin-collector-1 Recreated + Container mtusi-lab7-kraykin-collector-store-1 Recreate + Container mtusi-lab7-kraykin-postgres-1 Recreated + Container mtusi-lab7-kraykin-migrate-1 Recreate + Container mtusi-lab7-kraykin-cache-store-1 Recreated + Container mtusi-lab7-kraykin-collector-store-1 Recreated + Container mtusi-lab7-kraykin-broker-store-1 Recreated + Container mtusi-lab7-kraykin-migrate-1 Recreated + Container mtusi-lab7-kraykin-prometheus-store-1 Recreated + Container mtusi-lab7-kraykin-s3-store-1 Recreated + Container mtusi-lab7-kraykin-s3-init-1 Recreate + Container mtusi-lab7-kraykin-tempo-store-1 Recreated + Container mtusi-lab7-kraykin-loki-store-1 Recreated + Container mtusi-lab7-kraykin-grafana-store-1 Recreated + Container mtusi-lab7-kraykin-s3-init-1 Recreated + Container mtusi-lab7-kraykin-openbao-1 Recreated + Container mtusi-lab7-kraykin-dispatcher-1 Recreate + Container mtusi-lab7-kraykin-worker-1 Recreate + Container mtusi-lab7-kraykin-api-2 Recreate + Container mtusi-lab7-kraykin-api-1 Recreate + Container mtusi-lab7-kraykin-housekeeping-1 Recreate + Container mtusi-lab7-kraykin-housekeeping-1 Recreated + Container mtusi-lab7-kraykin-dispatcher-1 Recreated + Container mtusi-lab7-kraykin-api-1 Recreated + Container mtusi-lab7-kraykin-api-2 Recreated + Container mtusi-lab7-kraykin-lb-1 Recreate + Container mtusi-lab7-kraykin-worker-1 Recreated + Container mtusi-lab7-kraykin-lb-1 Recreated + Container mtusi-lab7-kraykin-prometheus-1 Starting + Container mtusi-lab7-kraykin-collector-1 Starting + Container mtusi-lab7-kraykin-postgres-1 Starting + Container mtusi-lab7-kraykin-tempo-1 Starting + Container mtusi-lab7-kraykin-loki-1 Starting + Container mtusi-lab7-kraykin-storage-init-1 Starting + Container mtusi-lab7-kraykin-broker-1 Starting + Container mtusi-lab7-kraykin-cache-1 Starting + Container mtusi-lab7-kraykin-s3-1 Starting + Container mtusi-lab7-kraykin-grafana-1 Starting + Container mtusi-lab7-kraykin-tempo-1 Started + Container mtusi-lab7-kraykin-tempo-store-1 Starting + Container mtusi-lab7-kraykin-prometheus-1 Started + Container mtusi-lab7-kraykin-prometheus-store-1 Starting + Container mtusi-lab7-kraykin-broker-1 Started + Container mtusi-lab7-kraykin-broker-store-1 Starting + Container mtusi-lab7-kraykin-grafana-1 Started + Container mtusi-lab7-kraykin-grafana-store-1 Starting + Container mtusi-lab7-kraykin-prometheus-store-1 Started + Container mtusi-lab7-kraykin-tempo-store-1 Started + Container mtusi-lab7-kraykin-cache-1 Started + Container mtusi-lab7-kraykin-cache-store-1 Starting + Container mtusi-lab7-kraykin-s3-1 Started + Container mtusi-lab7-kraykin-s3-store-1 Starting + Container mtusi-lab7-kraykin-storage-init-1 Started + Container mtusi-lab7-kraykin-storage-init-1 Waiting + Container mtusi-lab7-kraykin-broker-store-1 Started + Container mtusi-lab7-kraykin-loki-1 Started + Container mtusi-lab7-kraykin-loki-store-1 Starting + Container mtusi-lab7-kraykin-postgres-1 Started + Container mtusi-lab7-kraykin-postgres-1 Waiting + Container mtusi-lab7-kraykin-cache-store-1 Started + Container mtusi-lab7-kraykin-grafana-store-1 Started + Container mtusi-lab7-kraykin-collector-1 Started + Container mtusi-lab7-kraykin-collector-store-1 Starting + Container mtusi-lab7-kraykin-s3-store-1 Started + Container mtusi-lab7-kraykin-s3-init-1 Starting + Container mtusi-lab7-kraykin-loki-store-1 Started + Container mtusi-lab7-kraykin-collector-store-1 Started + Container mtusi-lab7-kraykin-s3-init-1 Started + Container mtusi-lab7-kraykin-storage-init-1 Exited + Container mtusi-lab7-kraykin-openbao-1 Starting + Container mtusi-lab7-kraykin-openbao-1 Started + Container mtusi-lab7-kraykin-postgres-1 Healthy + Container mtusi-lab7-kraykin-migrate-1 Starting + Container mtusi-lab7-kraykin-migrate-1 Started + Container mtusi-lab7-kraykin-migrate-1 Waiting + Container mtusi-lab7-kraykin-s3-init-1 Waiting + Container mtusi-lab7-kraykin-migrate-1 Waiting + Container mtusi-lab7-kraykin-s3-init-1 Waiting + Container mtusi-lab7-kraykin-migrate-1 Waiting + Container mtusi-lab7-kraykin-s3-init-1 Waiting + Container mtusi-lab7-kraykin-s3-init-1 Waiting + Container mtusi-lab7-kraykin-migrate-1 Waiting + Container mtusi-lab7-kraykin-migrate-1 Exited + Container mtusi-lab7-kraykin-migrate-1 Exited + Container mtusi-lab7-kraykin-migrate-1 Exited + Container mtusi-lab7-kraykin-migrate-1 Exited + Container mtusi-lab7-kraykin-s3-init-1 Exited + Container mtusi-lab7-kraykin-s3-init-1 Exited + Container mtusi-lab7-kraykin-worker-1 Starting + Container mtusi-lab7-kraykin-dispatcher-1 Starting + Container mtusi-lab7-kraykin-s3-init-1 Exited + Container mtusi-lab7-kraykin-housekeeping-1 Starting + Container mtusi-lab7-kraykin-s3-init-1 Exited + Container mtusi-lab7-kraykin-api-2 Starting + Container mtusi-lab7-kraykin-api-2 Started + Container mtusi-lab7-kraykin-api-1 Starting + Container mtusi-lab7-kraykin-dispatcher-1 Started + Container mtusi-lab7-kraykin-worker-1 Started + Container mtusi-lab7-kraykin-housekeeping-1 Started + Container mtusi-lab7-kraykin-api-1 Started + Container mtusi-lab7-kraykin-lb-1 Starting + Container mtusi-lab7-kraykin-lb-1 Started +Scoped DB grants, service certificate auth, TTL60s policies, KV and HMAC audit configured; no private output. +HTTPS/mTLS application ready; certificate verification enabled. diff --git a/evidence/telemetry.json b/evidence/telemetry.json new file mode 100644 index 0000000..7f9c5f5 --- /dev/null +++ b/evidence/telemetry.json @@ -0,0 +1,285 @@ +{ + "trace_id": "812db861dd0a4b93aa8807695b66f0b2", + "spans": [ + { + "service": "messenger-worker", + "name": "db.pool.acquire", + "id": "O2YRVKOYy6I=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.BEGIN", + "id": "ibl8t1nNTiU=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.SELECT", + "id": "MCcFjU/wpbc=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.SELECT", + "id": "huCq7TgJ61g=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.UPDATE", + "id": "NdsW/ZtRneo=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.UPDATE", + "id": "KV4p5MBESl0=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.INSERT", + "id": "aKL4ST7Emd0=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.COMMIT", + "id": "dtxWn9Ie0X8=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "s3.request", + "id": "u+1N60fie0E=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "image.transform", + "id": "dtW6UvyILt8=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "s3.request", + "id": "ljpUDpbkzKQ=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "s3.request", + "id": "cGI9hkbOsJ8=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "s3.request", + "id": "GlO6R2oKt0Q=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "s3.request", + "id": "l2f55D1Pcjw=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.pool.acquire", + "id": "z9lGAMvTtbM=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.BEGIN", + "id": "uJcDUteTSnc=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.SELECT", + "id": "EGnFkBgBqYw=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.UPDATE", + "id": "Fk9IhZKRVr8=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.UPDATE", + "id": "0/97k/31Ghg=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.INSERT", + "id": "W82YvgGP5MA=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.COMMIT", + "id": "zFFKbtJtSKk=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.pool.acquire", + "id": "5YaX+CjvQr0=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "db.SELECT", + "id": "bnzbV3PTapI=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "s3.request", + "id": "aGQDo93CpA8=", + "parent": "9uIhhOld4Qg=" + }, + { + "service": "messenger-worker", + "name": "queue.consume", + "id": "9uIhhOld4Qg=", + "parent": "R5U7TxrT3zQ=" + }, + { + "service": "messenger-dispatcher", + "name": "queue.publish", + "id": "R5U7TxrT3zQ=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.pool.acquire", + "id": "35IY3FPNKUk=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.SELECT", + "id": "+oHST1NpIO8=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.pool.acquire", + "id": "tGuqjrSBOhw=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.SELECT", + "id": "ouKeDW2Dq0I=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.pool.acquire", + "id": "YYdhyluyZrw=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.INSERT", + "id": "DiyP3QpIf7w=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.pool.acquire", + "id": "XsCx/KIGuQw=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.BEGIN", + "id": "UQajRvtw+3U=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.SELECT", + "id": "yDz3YACKb1Q=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "s3.request", + "id": "UxX7i4T/T4Y=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.INSERT", + "id": "fMpGQNiaGSM=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.SELECT", + "id": "JXpN2tfGZqs=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.SELECT", + "id": "Cqz3Pg+0XM8=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.INSERT", + "id": "qe+1wPlaTfc=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.DELETE", + "id": "18xzGgXSD7U=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "db.COMMIT", + "id": "u7x2LULtKYo=", + "parent": "Yn1H6K5Bxsg=" + }, + { + "service": "messenger-api", + "name": "POST /chats/{id}/attachments", + "id": "Yn1H6K5Bxsg=", + "parent": "6EfH5YuwShc=" + } + ], + "services": [ + "messenger-api", + "messenger-dispatcher", + "messenger-worker" + ], + "log_services": [ + "messenger-api", + "messenger-dispatcher", + "messenger-worker" + ], + "log_lines": 4, + "known_synthetic_tokens_passwords_absent": true, + "dashboard": { + "uid": "messenger-lab7", + "panels": 24 + }, + "actual_grafana_datasource_health": { + "prometheus": "actual query via Grafana proxy succeeded", + "loki": "actual query via Grafana proxy succeeded", + "tempo": "actual query via Grafana proxy succeeded" + }, + "network_protocol": "all queries and OTLP use verified TLS/mTLS; native loopback remains inside gateway boundary" +} diff --git a/evidence/telemetry.txt b/evidence/telemetry.txt new file mode 100644 index 0000000..f01d197 --- /dev/null +++ b/evidence/telemetry.txt @@ -0,0 +1 @@ +PASS: real TLS trace/log/metrics chain, privacy and all three provisioned Grafana datasource connections diff --git a/evidence/test-build.txt b/evidence/test-build.txt new file mode 100644 index 0000000..e8c91db --- /dev/null +++ b/evidence/test-build.txt @@ -0,0 +1,91 @@ +Compose can now delegate builds to bake for better performance. + To do so, set COMPOSE_BAKE=true. +#0 building with "desktop-linux" instance using docker driver + +#1 [tests internal] load build definition from Dockerfile +#1 transferring dockerfile: 1.11kB done +#1 DONE 0.0s + +#2 [tests internal] load metadata for docker.io/library/golang:1.27.4-alpine3.24 +#2 DONE 0.0s + +#3 [tests internal] load .dockerignore +#3 transferring context: 196B done +#3 DONE 0.0s + +#4 [tests internal] load build context +#4 DONE 0.0s + +#5 [tests build 1/7] FROM docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 +#5 resolve docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 +#5 resolve docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 4.3s done +#5 DONE 4.3s + +#4 [tests internal] load build context +#4 transferring context: 3.99kB done +#4 DONE 0.0s + +#6 [tests build 2/7] WORKDIR /src +#6 CACHED + +#7 [tests build 3/7] COPY go.mod go.sum ./ +#7 CACHED + +#8 [tests build 4/7] RUN --mount=type=cache,target=/go/pkg/mod GODEBUG=http2client=0 GOPROXY="https://proxy.golang.org,direct" go mod download +#8 CACHED + +#9 [tests build 5/7] COPY cmd/ ./cmd/ +#9 CACHED + +#10 [tests build 6/7] COPY internal/ ./internal/ +#10 DONE 0.0s + +#11 [tests build 7/7] RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server +#11 DONE 12.0s + +#12 [tests tests 1/2] RUN apk add --no-cache gcc musl-dev libwebp-tools +#12 1.242 ( 1/22) Installing libgcc (15.2.0-r5) +#12 1.327 ( 2/22) Installing jansson (2.15.0-r0) +#12 1.411 ( 3/22) Installing libstdc++ (15.2.0-r5) +#12 1.529 ( 4/22) Installing zstd-libs (1.6.0-r1) +#12 1.628 ( 5/22) Installing binutils (2.45.1-r1) +#12 1.887 ( 6/22) Installing libgcc-static (15.2.0-r5) +#12 2.036 ( 7/22) Installing libgomp (15.2.0-r5) +#12 2.123 ( 8/22) Installing libatomic (15.2.0-r5) +#12 2.208 ( 9/22) Installing gmp (6.3.0-r4) +#12 2.298 (10/22) Installing isl26 (0.26-r2) +#12 2.411 (11/22) Installing mpfr4 (4.2.2-r0) +#12 2.508 (12/22) Installing mpc1 (1.3.1-r1) +#12 2.593 (13/22) Installing gcc (15.2.0-r5) +#12 5.309 (14/22) Installing giflib (5.2.2-r2) +#12 5.391 (15/22) Installing libjpeg-turbo (3.1.3-r0) +#12 5.484 (16/22) Installing libpng (1.6.59-r0) +#12 5.571 (17/22) Installing libsharpyuv (1.6.0-r0) +#12 5.652 (18/22) Installing libwebp (1.6.0-r0) +#12 5.746 (19/22) Installing libwebpdemux (1.6.0-r0) +#12 5.827 (20/22) Installing libwebpmux (1.6.0-r0) +#12 5.908 (21/22) Installing libwebp-tools (1.6.0-r0) +#12 5.994 (22/22) Installing musl-dev (1.2.6-r3) +#12 6.215 Executing busybox-1.37.0-r31.trigger +#12 6.219 OK: 176.0 MiB in 39 packages +#12 DONE 6.3s + +#13 [tests tests 2/2] RUN --mount=type=cache,target=/go/pkg/mod mkdir -p /opt/gomod && cp -a /go/pkg/mod/. /opt/gomod/ +#13 DONE 3.2s + +#14 [tests] exporting to image +#14 exporting layers +#14 exporting layers 13.8s done +#14 exporting manifest sha256:751c0994edb23c339d824f7b1b5ab34eead7fa86674f6b6a8730c0d29152b04f +#14 exporting manifest sha256:751c0994edb23c339d824f7b1b5ab34eead7fa86674f6b6a8730c0d29152b04f done +#14 exporting config sha256:76c5a99052717ce0a06ada850e20c70116ecfdfb4118ce3feb0f6d3eb8d8be41 0.0s done +#14 exporting attestation manifest sha256:e9c619fec55f2e37e9c1a48c415891c9ef6a3c305fab001795e11c73366f0c74 0.0s done +#14 exporting manifest list sha256:f6df1b400bba5b39f2293beb4bd9230788d0a240df1e278745d327d715443ebf done +#14 naming to docker.io/library/mtusi-messenger-tests:lab7 done +#14 unpacking to docker.io/library/mtusi-messenger-tests:lab7 +#14 unpacking to docker.io/library/mtusi-messenger-tests:lab7 3.9s done +#14 DONE 17.8s + +#15 [tests] resolving provenance for metadata file +#15 DONE 0.0s + tests Built diff --git a/evidence/trust-matrix.json b/evidence/trust-matrix.json new file mode 100644 index 0000000..d2fbe69 --- /dev/null +++ b/evidence/trust-matrix.json @@ -0,0 +1,239 @@ +[ + { + "target": "broker", + "positive": { + "ok": true + }, + "negative": { + "no_certificate": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "foreign_ca": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "wrong_identity_same_ca": { + "error_category": "tls_handshake_denied", + "ok": false + } + } + }, + { + "target": "collector", + "positive": { + "ok": true, + "status": 200, + "tls": true + }, + "negative": { + "no_certificate": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "foreign_ca": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "wrong_identity_same_ca": { + "error_category": "tls_handshake_denied", + "ok": false + } + } + }, + { + "target": "api1", + "positive": { + "ok": true, + "status": 200, + "tls": true + }, + "negative": { + "no_certificate": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "foreign_ca": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "wrong_identity_same_ca": { + "error_category": "tls_handshake_denied", + "ok": false + } + } + }, + { + "target": "api2", + "positive": { + "ok": true, + "status": 200, + "tls": true + }, + "negative": { + "no_certificate": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "foreign_ca": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "wrong_identity_same_ca": { + "error_category": "tls_handshake_denied", + "ok": false + } + } + }, + { + "target": "s3", + "positive": { + "ok": true, + "status": 200, + "tls": true + }, + "wrong_identity": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "wrong_ca": { + "error_category": "ca_verification_failed", + "ok": false + }, + "wrong_hostname": { + "error_category": "hostname_verification_failed", + "ok": false + } + }, + { + "target": "prometheus", + "positive": { + "ok": true, + "status": 200, + "tls": true + }, + "wrong_identity": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "wrong_ca": { + "error_category": "ca_verification_failed", + "ok": false + }, + "wrong_hostname": { + "error_category": "hostname_verification_failed", + "ok": false + } + }, + { + "target": "loki", + "positive": { + "ok": true, + "status": 200, + "tls": true + }, + "wrong_identity": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "wrong_ca": { + "error_category": "ca_verification_failed", + "ok": false + }, + "wrong_hostname": { + "error_category": "hostname_verification_failed", + "ok": false + } + }, + { + "target": "tempo", + "positive": { + "ok": true, + "status": 200, + "tls": true + }, + "wrong_identity": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "wrong_ca": { + "error_category": "ca_verification_failed", + "ok": false + }, + "wrong_hostname": { + "error_category": "hostname_verification_failed", + "ok": false + } + }, + { + "target": "collector_metrics", + "positive": { + "ok": true, + "status": 200, + "tls": true + }, + "wrong_identity": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "wrong_ca": { + "error_category": "ca_verification_failed", + "ok": false + }, + "wrong_hostname": { + "error_category": "hostname_verification_failed", + "ok": false + } + }, + { + "target": "ingress_metrics", + "positive": { + "ok": true, + "status": 200, + "tls": true + }, + "wrong_identity": { + "ok": false, + "status": 403, + "tls": true + }, + "wrong_ca": { + "error_category": "ca_verification_failed", + "ok": false + }, + "wrong_hostname": { + "error_category": "hostname_verification_failed", + "ok": false + } + }, + { + "target": "postgres_api", + "positive": { + "ok": true + }, + "wrong_ca": { + "error_category": "ca_verification_failed", + "ok": false + } + }, + { + "target": "postgres_worker", + "positive": { + "ok": true + }, + "wrong_ca": { + "error_category": "ca_verification_failed", + "ok": false + } + }, + { + "target": "cache", + "positive": { + "ok": true + }, + "wrong_identity": { + "error_category": "tls_handshake_denied", + "ok": false + } + } +] diff --git a/evidence/worker-compromise-first.json b/evidence/worker-compromise-first.json new file mode 100644 index 0000000..bba4539 --- /dev/null +++ b/evidence/worker-compromise-first.json @@ -0,0 +1,103 @@ +{ + "model": "exfiltrated live worker leaf+service credentials, no host/Docker/CA compromise; operator probes use only selected worker identity; baseline is a deliberately overprivileged test fixture, never mounted into runtime worker", + "images_before": [ + "6e202c00610daf051d71449e414f6d1a285da1a89ea49c4bb12e0528d5378ce2" + ], + "before_least_privilege": { + "password_table": { + "ok": true + }, + "bucket_administration": { + "ok": true + } + }, + "accepted_while_quarantined": 8, + "least_privilege": { + "allowed": { + "db_pipeline": { + "ok": true + }, + "s3_staging": { + "ok": true + }, + "queue_ping": { + "ok": true + } + }, + "denied": { + "password_table": { + "error_category": "permission_denied", + "ok": false + }, + "sessions": { + "error_category": "permission_denied", + "ok": false + }, + "messages": { + "error_category": "permission_denied", + "ok": false + }, + "change_owner": { + "error_category": "permission_denied", + "ok": false + }, + "drop_table": { + "error_category": "permission_denied", + "ok": false + }, + "s3_private_prefix": { + "error_category": "permission_denied", + "ok": false + }, + "s3_staging_write": { + "error_category": "permission_denied", + "ok": false + }, + "bucket_administration": { + "error_category": "permission_denied", + "ok": false + }, + "queue_publish": { + "error_category": "permission_denied", + "ok": false + }, + "queue_flush": { + "error_category": "permission_denied", + "ok": false + }, + "queue_other_key": { + "error_category": "permission_denied", + "ok": false + }, + "bao_api_secret": { + "ok": false, + "error_category": "policy_denied" + } + } + }, + "after_revocation": { + "old_cert_queue": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "old_cert_s3": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "old_bao_token_denied": true, + "old_sql_password": { + "error_category": "credential_denied", + "ok": false + } + }, + "recovery_all_ready_seconds": 4.101, + "all_accepted_originals_identical": true, + "background_messages_success": 98, + "background_messages_errors": 2, + "images_after": [ + "6e202c00610daf051d71449e414f6d1a285da1a89ea49c4bb12e0528d5378ce2" + ], + "new_worker_connects": { + "ok": true + } +} diff --git a/evidence/worker-compromise.json b/evidence/worker-compromise.json new file mode 100644 index 0000000..f149e3c --- /dev/null +++ b/evidence/worker-compromise.json @@ -0,0 +1,117 @@ +{ + "model": "exfiltrated live worker leaf+service credentials, no host/Docker/CA compromise; operator probes use only selected worker identity; baseline is a deliberately overprivileged test fixture, never mounted into runtime worker", + "images_before": [ + "cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245" + ], + "before_least_privilege": { + "password_table": { + "ok": true + }, + "bucket_administration": { + "ok": true + } + }, + "accepted_while_quarantined": 8, + "least_privilege": { + "allowed": { + "db_pipeline": { + "ok": true + }, + "db_execution_update": { + "ok": true + }, + "s3_staging": { + "ok": true + }, + "s3_final_put": { + "ok": true + }, + "queue_ping": { + "ok": true + } + }, + "denied": { + "password_table": { + "error_category": "permission_denied", + "ok": false + }, + "sessions": { + "error_category": "permission_denied", + "ok": false + }, + "messages": { + "error_category": "permission_denied", + "ok": false + }, + "change_owner": { + "error_category": "permission_denied", + "ok": false + }, + "change_checksum": { + "error_category": "permission_denied", + "ok": false + }, + "drop_table": { + "error_category": "permission_denied", + "ok": false + }, + "s3_private_prefix": { + "error_category": "permission_denied", + "ok": false + }, + "s3_staging_write": { + "error_category": "permission_denied", + "ok": false + }, + "s3_final_delete": { + "error_category": "permission_denied", + "ok": false + }, + "bucket_administration": { + "error_category": "permission_denied", + "ok": false + }, + "queue_publish": { + "error_category": "permission_denied", + "ok": false + }, + "queue_flush": { + "error_category": "permission_denied", + "ok": false + }, + "queue_other_key": { + "error_category": "permission_denied", + "ok": false + }, + "bao_api_secret": { + "ok": false, + "error_category": "policy_denied" + } + } + }, + "after_revocation": { + "old_cert_queue": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "old_cert_s3": { + "error_category": "tls_handshake_denied", + "ok": false + }, + "old_bao_token_denied": true, + "old_sql_password": { + "error_category": "credential_denied", + "ok": false + } + }, + "recovery_all_ready_seconds": 3.823, + "all_accepted_originals_identical": true, + "background_messages_success": 80, + "background_messages_errors": 0, + "images_after": [ + "cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245" + ], + "new_worker_connects": { + "ok": true + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..5af5a7e --- /dev/null +++ b/go.mod @@ -0,0 +1,57 @@ +module mtusi/messenger + +go 1.27.0 + +require ( + github.com/disintegration/imaging v1.6.2 + github.com/jackc/pgx/v5 v5.9.2 + github.com/minio/minio-go/v7 v7.0.95 + github.com/redis/go-redis/v9 v9.12.1 + go.opentelemetry.io/contrib/bridges/otelslog v0.21.0 + go.opentelemetry.io/otel v1.47.0 + go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 + go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 + go.opentelemetry.io/otel/metric v1.47.0 + go.opentelemetry.io/otel/sdk v1.47.0 + go.opentelemetry.io/otel/sdk/log v1.47.0 + go.opentelemetry.io/otel/sdk/metric v1.47.0 + go.opentelemetry.io/otel/trace v1.47.0 + golang.org/x/crypto v0.59.0 +) + +require ( + github.com/cenkalti/backoff/v5 v5.0.3 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-ini/ini v1.67.0 // indirect + github.com/go-logr/logr v1.4.4 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/klauspost/compress v1.20.2 // indirect + github.com/klauspost/cpuid/v2 v2.2.11 // indirect + github.com/minio/crc64nvme v1.0.2 // indirect + github.com/minio/md5-simd v1.1.2 // indirect + github.com/philhofer/fwd v1.2.0 // indirect + github.com/rs/xid v1.6.0 // indirect + github.com/tinylib/msgp v1.3.0 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect + go.opentelemetry.io/otel/log v1.47.0 // indirect + go.opentelemetry.io/proto/otlp v1.11.0 // indirect + golang.org/x/image v0.45.0 // indirect + golang.org/x/net v0.63.0 // indirect + golang.org/x/sync v0.25.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/text v0.44.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect + google.golang.org/grpc v1.83.2 // indirect + google.golang.org/protobuf v1.36.12 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e692909 --- /dev/null +++ b/go.sum @@ -0,0 +1,127 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c= +github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A= +github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw= +github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo= +github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU= +github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/minio/crc64nvme v1.0.2 h1:6uO1UxGAD+kwqWWp7mBFsi5gAse66C4NXO8cmcVculg= +github.com/minio/crc64nvme v1.0.2/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= +github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= +github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= +github.com/minio/minio-go/v7 v7.0.95 h1:ywOUPg+PebTMTzn9VDsoFJy32ZuARN9zhB+K3IYEvYU= +github.com/minio/minio-go/v7 v7.0.95/go.mod h1:wOOX3uxS334vImCNRVyIDdXX9OsXDm89ToynKgqUKlo= +github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= +github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.12.1 h1:k5iquqv27aBtnTm2tIkROUDp8JBXhXZIVu1InSgvovg= +github.com/redis/go-redis/v9 v9.12.1/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= +github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww= +github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/bridges/otelslog v0.21.0 h1:/CdgE52i1OEPHhsGUqrggYNRaZy4v4YgVenGd52dRBI= +go.opentelemetry.io/contrib/bridges/otelslog v0.21.0/go.mod h1:9pBdbVbuehIDzxN4accnzzxEUPT8Nq7grbZMo+J1VN4= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 h1:5WVp40k2fJHuc5BtNTgKk+EugKFT8Eg3lywFfCPI/nE= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0/go.mod h1:59nH0RYCGHRlwt15WyioeSYINBbuObeBpTowPhEKWHY= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0 h1:7kszRN4Ze5GeAkUnBjBSUIunVBMA+mZIG04auueqguM= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0/go.mod h1:CLzakYy8jOdkBfcveCWYkeKJxujcF4xPhh2Z7IfE98U= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= +go.opentelemetry.io/otel/metric/x v0.69.0 h1:DjRLr15H83v+hCW7JA9NoJvOkYTtmq5YoDRbe9deYpM= +go.opentelemetry.io/otel/metric/x v0.69.0/go.mod h1:uVvsMPMFFyj/HUQfrUnH3JjnOQ1dwFDorgFLRBasM0k= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= +go.opentelemetry.io/otel/sdk/log v1.47.0 h1:W4N/ZfgpkRRnmARnqYoQ6BrWA0mrj8IzVDNLlpmUJZY= +go.opentelemetry.io/otel/sdk/log v1.47.0/go.mod h1:Wu74Z2EmOKXi2FleSNAb0Hyau2G+r5kubSEMJw5aAMs= +go.opentelemetry.io/otel/sdk/log/logtest v0.23.0 h1:j3pm42QCrKYYLLkI6OrV1QHFkUfDA6/4EP+Y1PzggLg= +go.opentelemetry.io/otel/sdk/log/logtest v0.23.0/go.mod h1:zt0gEnuTZgDvqvczHwYswz93eqMaIr6upTTsdV/HUlU= +go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw= +go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= +go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= +go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0= +golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4= +golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= +golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc h1:rZHRz0ogq4Pid1IKtA/ivHi8XONVF5tqUQXA2TtgpkE= +google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:K/n0XLazCJHjD73YuMyNJsN38BPPy1kfFnKxUXaThFU= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= +google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/infra/grafana-start.sh b/infra/grafana-start.sh new file mode 100644 index 0000000..85dae1c --- /dev/null +++ b/infra/grafana-start.sh @@ -0,0 +1,7 @@ +#!/bin/sh +set -eu +# Grafana provisioning accepts PEM values, not file paths; keep only in memory. +export TLS_CA_CONTENT="$(cat /run/tls/ca.crt)" +export TLS_CERT_CONTENT="$(cat /run/tls/cert.crt)" +export TLS_KEY_CONTENT="$(cat /run/tls/key.key)" +exec /run.sh diff --git a/infra/grafana/dashboards/messenger.json b/infra/grafana/dashboards/messenger.json new file mode 100644 index 0000000..41db218 --- /dev/null +++ b/infra/grafana/dashboards/messenger.json @@ -0,0 +1,697 @@ +{ + "uid": "messenger-lab7", + "title": "Messenger: API and image pipeline", + "schemaVersion": 39, + "version": 1, + "refresh": "5s", + "time": { + "from": "now-15m", + "to": "now" + }, + "tags": [ + "highload", + "lab6" + ], + "panels": [ + { + "id": 1, + "title": "API successful / error RPS (business only)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 0, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (status_class) (rate(http_server_requests_total{route!~\"/health.*\"}[30s]))", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps" + }, + "overrides": [] + } + }, + { + "id": 2, + "title": "API 5xx ratio", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 0, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "(sum(rate(http_server_requests_total{route!~\"/health.*\",status_class=\"5xx\"}[30s])) or vector(0)) / clamp_min(sum(rate(http_server_requests_total{route!~\"/health.*\"}[30s])),0.001)", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + } + }, + { + "id": 3, + "title": "API p50 across replicas (histogram)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 8, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.5,sum by(le)(rate(http_server_duration_seconds_bucket{route!~\"/health.*\"}[60s])))", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + } + }, + { + "id": 4, + "title": "API p95 across replicas (histogram)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 8, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.95,sum by(le)(rate(http_server_duration_seconds_bucket{route!~\"/health.*\"}[60s])))", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + } + }, + { + "id": 5, + "title": "API p99 across replicas (histogram)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 16, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.99,sum by(le)(rate(http_server_duration_seconds_bucket{route!~\"/health.*\"}[60s])))", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + } + }, + { + "id": 6, + "title": "Worker attempt outcomes / second", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 16, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "sum by(outcome)(rate(messenger_jobs_total[60s]))", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + } + }, + { + "id": 7, + "title": "Worker processing p95", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 24, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(.95,sum by(le)(rate(messenger_job_duration_seconds_bucket[60s])))", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + } + }, + { + "id": 8, + "title": "Time to ready p95 (completed)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 24, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(.95,sum by(le)(rate(messenger_attachment_ready_duration_seconds_bucket[60s])))", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + } + }, + { + "id": 9, + "title": "Outstanding jobs (DB authority, includes processing)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 32, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "max(messenger_queue_depth)", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + }, + { + "id": 10, + "title": "Oldest unfinished age", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 32, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "max(messenger_queue_oldest_age_seconds)", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + } + }, + { + "id": 11, + "title": "Worker saturation busy / capacity", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 40, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "sum(messenger_worker_busy)/clamp_min(sum(messenger_worker_capacity),1)", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + } + }, + { + "id": 12, + "title": "DB acquired / max", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 40, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "messenger_db_pool_used / messenger_db_pool_limit", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + } + }, + { + "id": 13, + "title": "DB pool empty acquire events / second", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 48, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "rate(messenger_db_pool_waits_total[60s])", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops" + }, + "overrides": [] + } + }, + { + "id": 14, + "title": "Process RSS (parent, excludes transform child)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 48, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "process_memory_usage_bytes", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes" + }, + "overrides": [] + } + }, + { + "id": 15, + "title": "Process CPU cores (parent, excludes transform child)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 56, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "rate(process_cpu_time_seconds_total[60s])", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + }, + { + "id": 16, + "title": "Ready SLI bad ratio 10m, includes unfinished >5s", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 56, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "sum(increase(messenger_attachment_sli_bad_total[10m])) / clamp_min(sum(increase(messenger_attachment_sli_total[10m])),1)", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + } + }, + { + "id": 17, + "title": "Ingress API availability SLI 10m (includes LB 503)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 64, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "1-(sum(increase(haproxy_backend_http_responses_total{proxy=\"replicas\",code=\"5xx\"}[10m])) or vector(0))/clamp_min(sum(increase(haproxy_backend_http_responses_total{proxy=\"replicas\"}[10m])),1)", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit" + }, + "overrides": [] + } + }, + { + "id": 18, + "title": "Collector dropped spans (counter)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 64, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "sum(otelcol_exporter_send_failed_spans_total)", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + }, + { + "id": 19, + "title": "API structured logs", + "type": "logs", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "gridPos": { + "x": 0, + "y": 72, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "{service_name=\"messenger-api\"}", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + }, + { + "id": 20, + "title": "Worker structured logs", + "type": "logs", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "gridPos": { + "x": 12, + "y": 72, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "{service_name=\"messenger-worker\"}", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + }, + { + "id": 21, + "title": "Firing alerts", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 80, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "ALERTS{alertstate=\"firing\"}", + "legendFormat": "{{service_name}} {{outcome}} {{quantile}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + }, + { + "id": 22, + "title": "Container RAM including transform children", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 80, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "container_memory_usage_bytes", + "legendFormat": "{{service_name}} {{service_instance_id}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes" + }, + "overrides": [] + } + }, + { + "id": 23, + "title": "Container CPU cores including transform children", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 88, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "rate(container_cpu_time_seconds_total[60s])", + "legendFormat": "{{service_name}} {{service_instance_id}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + }, + { + "id": 24, + "title": "DB pending acquire calls (current)", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, + "y": 88, + "w": 12, + "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "messenger_db_pool_waiting", + "legendFormat": "{{service_name}} {{service_instance_id}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short" + }, + "overrides": [] + } + } + ], + "links": [ + { + "title": "Tempo traces", + "type": "link", + "url": "/explore?left=%7B%22datasource%22:%22tempo%22%7D", + "targetBlank": true + } + ] +} diff --git a/infra/grafana/provisioning/dashboards/default.yaml b/infra/grafana/provisioning/dashboards/default.yaml new file mode 100644 index 0000000..8d42c19 --- /dev/null +++ b/infra/grafana/provisioning/dashboards/default.yaml @@ -0,0 +1,6 @@ +apiVersion: 1 +providers: + - name: Messenger + folder: Highload labs + type: file + options: {path: /var/lib/grafana/dashboards} diff --git a/infra/grafana/provisioning/datasources/sources.yaml b/infra/grafana/provisioning/datasources/sources.yaml new file mode 100644 index 0000000..da9c0b7 --- /dev/null +++ b/infra/grafana/provisioning/datasources/sources.yaml @@ -0,0 +1,40 @@ +apiVersion: 1 +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: https://prometheus:9090 + isDefault: true + jsonData: {tlsAuth: true, tlsAuthWithCACert: true, httpMethod: GET} + secureJsonData: {tlsCACert: '${TLS_CA_CONTENT}', tlsClientCert: '${TLS_CERT_CONTENT}', tlsClientKey: '${TLS_KEY_CONTENT}'} + - name: Loki + uid: loki + type: loki + access: proxy + url: https://loki:3100 + secureJsonData: {tlsCACert: '${TLS_CA_CONTENT}', tlsClientCert: '${TLS_CERT_CONTENT}', tlsClientKey: '${TLS_KEY_CONTENT}'} + jsonData: + tlsAuth: true + tlsAuthWithCACert: true + derivedFields: + - name: TraceID + matcherRegex: trace_id + matcherType: label + datasourceUid: tempo + url: '$${__value.raw}' + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: https://tempo:3200 + secureJsonData: {tlsCACert: '${TLS_CA_CONTENT}', tlsClientCert: '${TLS_CERT_CONTENT}', tlsClientKey: '${TLS_KEY_CONTENT}'} + jsonData: + tlsAuth: true + tlsAuthWithCACert: true + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: '-1m' + spanEndTimeShift: '1m' + filterByTraceID: true + filterBySpanID: false diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg new file mode 100644 index 0000000..fadc867 --- /dev/null +++ b/infra/haproxy.cfg @@ -0,0 +1,41 @@ +global + maxconn 512 + log stdout format raw local0 + ssl-default-bind-options ssl-min-ver TLSv1.2 + ssl-default-server-options ssl-min-ver TLSv1.2 +defaults + log global + mode http + timeout connect 800ms + timeout client 35s + timeout server 35s + timeout check 1500ms + retries 0 +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 2 + timeout resolve 1s + timeout retry 1s + hold valid 1s + hold obsolete 1s +frontend public + bind :8443 ssl crt /run/tls/full.pem + http-response set-header Strict-Transport-Security max-age=86400 + use_backend readiness if { path_beg /health/ } + default_backend replicas +backend replicas + balance roundrobin + option httpchk GET /health/ready + http-check expect status 200 + default-server inter 1s fall 2 rise 1 + server-template api 4 api:8080 ssl verify required ca-file /run/tls/ca.crt crt /run/tls/full.pem sni str(api) verifyhost api check resolvers docker init-addr libc,none resolve-prefer ipv4 +backend readiness + balance roundrobin + option httpchk GET /health/ready + http-check expect status 200 + default-server inter 1s fall 2 rise 1 + server-template api 4 api:8080 ssl verify required ca-file /run/tls/ca.crt crt /run/tls/full.pem sni str(api) verifyhost api check resolvers docker init-addr libc,none resolve-prefer ipv4 +frontend metrics + bind :8404 ssl crt /run/tls/full.pem ca-file /run/tls/ca.crt verify required + http-request deny unless { ssl_c_s_dn(CN) -m str prometheus } + http-request use-service prometheus-exporter if { path /metrics } diff --git a/infra/loki/loki.yaml b/infra/loki/loki.yaml new file mode 100644 index 0000000..c40887b --- /dev/null +++ b/infra/loki/loki.yaml @@ -0,0 +1,29 @@ +auth_enabled: false +server: {http_listen_address: 127.0.0.1, http_listen_port: 3101, grpc_listen_address: 127.0.0.1} +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + storage: + filesystem: {chunks_directory: /loki/chunks, rules_directory: /loki/rules} + replication_factor: 1 + ring: {kvstore: {store: inmemory}} +schema_config: + configs: + - from: '2024-01-01' + store: tsdb + object_store: filesystem + schema: v13 + index: {prefix: index_, period: 24h} +limits_config: + allow_structured_metadata: true + retention_period: 24h + otlp_config: + resource_attributes: + attributes_config: + - action: structured_metadata + attributes: [service.instance.id] +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem +analytics: {reporting_enabled: false} diff --git a/infra/openbao/policies/api.hcl b/infra/openbao/policies/api.hcl new file mode 100644 index 0000000..8b32e40 --- /dev/null +++ b/infra/openbao/policies/api.hcl @@ -0,0 +1,3 @@ +path "kv/data/api" { capabilities = ["read"] } +path "auth/token/lookup-self" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/openbao/policies/dispatcher.hcl b/infra/openbao/policies/dispatcher.hcl new file mode 100644 index 0000000..3187d53 --- /dev/null +++ b/infra/openbao/policies/dispatcher.hcl @@ -0,0 +1,3 @@ +path "kv/data/dispatcher" { capabilities = ["read"] } +path "auth/token/lookup-self" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/openbao/policies/housekeeping.hcl b/infra/openbao/policies/housekeeping.hcl new file mode 100644 index 0000000..c88e914 --- /dev/null +++ b/infra/openbao/policies/housekeeping.hcl @@ -0,0 +1,3 @@ +path "kv/data/housekeeping" { capabilities = ["read"] } +path "auth/token/lookup-self" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/openbao/policies/worker.hcl b/infra/openbao/policies/worker.hcl new file mode 100644 index 0000000..7aaa927 --- /dev/null +++ b/infra/openbao/policies/worker.hcl @@ -0,0 +1,3 @@ +path "kv/data/worker" { capabilities = ["read"] } +path "auth/token/lookup-self" { capabilities = ["read"] } +path "auth/token/revoke-self" { capabilities = ["update"] } diff --git a/infra/openbao/server.hcl b/infra/openbao/server.hcl new file mode 100644 index 0000000..6a6f03b --- /dev/null +++ b/infra/openbao/server.hcl @@ -0,0 +1,21 @@ +ui = false +api_addr = "https://openbao:8200" +cluster_addr = "https://openbao:8201" +storage "raft" { + path = "/bao/data/raft-v2" + node_id = "lab7" + performance_multiplier = 1 +} +listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/run/tls/cert.crt" + tls_key_file = "/run/tls/key.key" + tls_client_ca_file = "/run/tls/ca.crt" + tls_min_version = "tls12" +} +default_lease_ttl = "60s" +max_lease_ttl = "120s" +audit "file" "file" { + description = "Operator-owned persistent HMAC audit" + options { file_path = "/bao/audit/audit.json" } +} diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 0000000..67edcb8 --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,35 @@ +receivers: + otlp: + protocols: + http: {endpoint: '127.0.0.1:4319'} +processors: + memory_limiter: {check_interval: 1s, limit_mib: 180, spike_limit_mib: 40} + batch: {timeout: 1s, send_batch_size: 128, send_batch_max_size: 256} +exporters: + prometheus: + endpoint: '127.0.0.1:8891' + resource_to_telemetry_conversion: {enabled: true} + otlphttp/tempo: + endpoint: https://tempo:4318 + tls: {ca_file: /run/tls/ca.crt, cert_file: /run/tls/cert.crt, key_file: /run/tls/key.key} + timeout: 2s + retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 5s, max_elapsed_time: 15s} + sending_queue: {enabled: true, num_consumers: 2, queue_size: 64} + otlphttp/loki: + endpoint: https://loki:3100/otlp + tls: {ca_file: /run/tls/ca.crt, cert_file: /run/tls/cert.crt, key_file: /run/tls/key.key} + timeout: 2s + retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 5s, max_elapsed_time: 15s} + sending_queue: {enabled: true, num_consumers: 2, queue_size: 64} +service: + telemetry: + metrics: + level: detailed + readers: + - pull: + exporter: + prometheus: {host: 127.0.0.1, port: 8890} + pipelines: + traces: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/tempo]} + metrics: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [prometheus]} + logs: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/loki]} diff --git a/infra/pg_hba.conf b/infra/pg_hba.conf new file mode 100644 index 0000000..b1953e4 --- /dev/null +++ b/infra/pg_hba.conf @@ -0,0 +1,3 @@ +local all all trust +hostnossl all all all reject +hostssl messenger all all scram-sha-256 diff --git a/infra/postgres-start.sh b/infra/postgres-start.sh new file mode 100644 index 0000000..072ad7a --- /dev/null +++ b/infra/postgres-start.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu +mkdir -p /tmp/pg-tls +cp /run/tls/cert.crt /tmp/pg-tls/cert.crt +cp /run/tls/key.key /tmp/pg-tls/key.key +chown -R postgres:postgres /tmp/pg-tls +chmod 600 /tmp/pg-tls/key.key +exec /usr/local/bin/docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/tmp/pg-tls/cert.crt -c ssl_key_file=/tmp/pg-tls/key.key -c hba_file=/config/pg_hba.conf -c password_encryption=scram-sha-256 diff --git a/infra/prometheus/alerts.yaml b/infra/prometheus/alerts.yaml new file mode 100644 index 0000000..19a4632 --- /dev/null +++ b/infra/prometheus/alerts.yaml @@ -0,0 +1,29 @@ +groups: + - name: messenger + interval: 2s + rules: + - alert: APIHighErrorRate + expr: (sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[30s])) or vector(0)) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[30s])), 0.001) > 0.1 + for: 6s + labels: {severity: warning} + annotations: {summary: 'API 5xx above 10% for 30s window', runbook: 'RUNBOOK.md#db'} + - alert: QueueLag + expr: max(messenger_queue_oldest_age_seconds) > 5 and max(messenger_queue_depth) > 0 + for: 6s + labels: {severity: warning} + annotations: {summary: 'Oldest unfinished job exceeds 5s', runbook: 'RUNBOOK.md#worker'} + - alert: APIBudgetFastBurn + expr: ((sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[10s])) or vector(0)) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[10s])),0.001) > 6 * 0.01) and ((sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[60s])) or vector(0)) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[60s])),0.001) > 6 * 0.01) + for: 10s + labels: {severity: critical, slo: api_99} + annotations: {summary: 'API budget burn >6x in 10s and 60s', runbook: 'RUNBOOK.md#db'} + - alert: APIBudgetSlowBurn + expr: ((sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[30s])) or vector(0)) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[30s])),0.001) > 2 * 0.01) and ((sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[120s])) or vector(0)) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[120s])),0.001) > 2 * 0.01) + for: 20s + labels: {severity: warning, slo: api_99} + annotations: {summary: 'API budget burn >2x in 30s and 120s', runbook: 'RUNBOOK.md#db'} + - alert: ReadyBudgetFastBurn + expr: (sum(rate(messenger_attachment_sli_bad_total[10s])) / clamp_min(sum(rate(messenger_attachment_sli_total[10s])),0.001) > 6 * 0.05) and (sum(rate(messenger_attachment_sli_bad_total[60s])) / clamp_min(sum(rate(messenger_attachment_sli_total[60s])),0.001) > 6 * 0.05) + for: 10s + labels: {severity: critical, slo: ready_95} + annotations: {summary: 'Ready deadline budget burn >6x in 10s and 60s', runbook: 'RUNBOOK.md#worker'} diff --git a/infra/prometheus/prometheus.yaml b/infra/prometheus/prometheus.yaml new file mode 100644 index 0000000..fbcb609 --- /dev/null +++ b/infra/prometheus/prometheus.yaml @@ -0,0 +1,15 @@ +global: {scrape_interval: 2s, evaluation_interval: 2s} +rule_files: [/etc/prometheus/alerts.yaml] +scrape_configs: + - job_name: messenger + scheme: https + tls_config: {ca_file: /run/tls/ca.crt, cert_file: /run/tls/cert.crt, key_file: /run/tls/key.key} + static_configs: [{targets: ['collector:8889']}] + - job_name: collector + scheme: https + tls_config: {ca_file: /run/tls/ca.crt, cert_file: /run/tls/cert.crt, key_file: /run/tls/key.key} + static_configs: [{targets: ['collector:8888']}] + - job_name: ingress + scheme: https + tls_config: {ca_file: /run/tls/ca.crt, cert_file: /run/tls/cert.crt, key_file: /run/tls/key.key} + static_configs: [{targets: ['lb:8404']}] diff --git a/infra/s3/api.json b/infra/s3/api.json new file mode 100644 index 0000000..214d6c3 --- /dev/null +++ b/infra/s3/api.json @@ -0,0 +1,24 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:PutObject", + "s3:DeleteObject" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments/staging/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:GetObject" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments/originals/*" + ] + } + ] +} diff --git a/infra/s3/housekeeping.json b/infra/s3/housekeeping.json new file mode 100644 index 0000000..ea10944 --- /dev/null +++ b/infra/s3/housekeeping.json @@ -0,0 +1,31 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:DeleteObject" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments/staging/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:ListBucket" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments" + ], + "Condition": { + "StringLike": { + "s3:prefix": [ + "staging/*" + ] + } + } + } + ] +} diff --git a/infra/s3/s3-init.sh b/infra/s3/s3-init.sh new file mode 100644 index 0000000..14b7eca --- /dev/null +++ b/infra/s3/s3-init.sh @@ -0,0 +1,17 @@ +#!/bin/sh +set -eu +. /run/operator/users.sh +until mc alias set local http://127.0.0.1:9001 "$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null 2>&1; do sleep 1; done +mc mb --ignore-existing local/messenger-attachments >/dev/null +mc anonymous set none local/messenger-attachments >/dev/null +for role in api worker housekeeping; do + mc admin policy create local "lab7-$role" "/config/$role.json" >/dev/null + case "$role" in + api) access=$API_S3_ACCESS_KEY_ID; secret=$API_S3_SECRET_ACCESS_KEY;; + worker) access=$WORKER_S3_ACCESS_KEY_ID; secret=$WORKER_S3_SECRET_ACCESS_KEY;; + housekeeping) access=$HOUSEKEEPING_S3_ACCESS_KEY_ID; secret=$HOUSEKEEPING_S3_SECRET_ACCESS_KEY;; + esac + mc admin user add local "$access" "$secret" >/dev/null + mc admin policy attach local "lab7-$role" --user "$access" >/dev/null +done +printf '%s\n' 'Private bucket with separate prefix-scoped identities ready' diff --git a/infra/s3/worker.json b/infra/s3/worker.json new file mode 100644 index 0000000..ef8c585 --- /dev/null +++ b/infra/s3/worker.json @@ -0,0 +1,24 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:GetObject" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments/staging/*", + "arn:aws:s3:::messenger-attachments/originals/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "s3:PutObject" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments/originals/*" + ] + } + ] +} diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml new file mode 100644 index 0000000..d7c7341 --- /dev/null +++ b/infra/tempo/tempo.yaml @@ -0,0 +1,17 @@ +server: {http_listen_address: 127.0.0.1, http_listen_port: 3201, grpc_listen_address: 127.0.0.1} +distributor: + receivers: + otlp: + protocols: + http: {endpoint: '127.0.0.1:4319'} +ingester: + trace_idle_period: 2s + max_block_duration: 5m +compactor: + compaction: {block_retention: 24h} +storage: + trace: + backend: local + local: {path: /var/tempo/blocks} + wal: {path: /var/tempo/wal} +usage_report: {reporting_enabled: false} diff --git a/infra/tls/broker.json b/infra/tls/broker.json new file mode 100644 index 0000000..9d4b300 --- /dev/null +++ b/infra/tls/broker.json @@ -0,0 +1,12 @@ +[ + { + "listen": ":6379", + "target": "127.0.0.1:6380", + "identities": [ + "worker", + "dispatcher", + "operator" + ], + "raw": true + } +] diff --git a/infra/tls/cache.json b/infra/tls/cache.json new file mode 100644 index 0000000..98af059 --- /dev/null +++ b/infra/tls/cache.json @@ -0,0 +1,11 @@ +[ + { + "listen": ":6379", + "target": "127.0.0.1:6380", + "identities": [ + "api", + "operator" + ], + "raw": true + } +] diff --git a/infra/tls/collector.json b/infra/tls/collector.json new file mode 100644 index 0000000..3b9fb44 --- /dev/null +++ b/infra/tls/collector.json @@ -0,0 +1,122 @@ +[ + { + "listen": ":4318", + "target": "127.0.0.1:4319", + "identities": [ + "api", + "worker", + "dispatcher", + "housekeeping" + ], + "rules": [ + { + "identity": "api", + "methods": [ + "POST" + ], + "prefixes": [ + "/v1/traces", + "/v1/logs", + "/v1/metrics" + ] + }, + { + "identity": "worker", + "methods": [ + "POST" + ], + "prefixes": [ + "/v1/traces", + "/v1/logs", + "/v1/metrics" + ] + }, + { + "identity": "dispatcher", + "methods": [ + "POST" + ], + "prefixes": [ + "/v1/traces", + "/v1/logs", + "/v1/metrics" + ] + }, + { + "identity": "housekeeping", + "methods": [ + "POST" + ], + "prefixes": [ + "/v1/traces", + "/v1/logs", + "/v1/metrics" + ] + } + ] + }, + { + "listen": ":8889", + "target": "127.0.0.1:8891", + "identities": [ + "prometheus", + "operator" + ], + "rules": [ + { + "identity": "prometheus", + "methods": [ + "GET" + ], + "prefixes": [ + "/metrics" + ] + }, + { + "identity": "operator", + "methods": [ + "GET", + "POST", + "PUT", + "DELETE", + "HEAD" + ], + "prefixes": [ + "/" + ] + } + ] + }, + { + "listen": ":8888", + "target": "127.0.0.1:8890", + "identities": [ + "prometheus", + "operator" + ], + "rules": [ + { + "identity": "prometheus", + "methods": [ + "GET" + ], + "prefixes": [ + "/metrics" + ] + }, + { + "identity": "operator", + "methods": [ + "GET", + "POST", + "PUT", + "DELETE", + "HEAD" + ], + "prefixes": [ + "/" + ] + } + ] + } +] diff --git a/infra/tls/grafana.json b/infra/tls/grafana.json new file mode 100644 index 0000000..e3d797c --- /dev/null +++ b/infra/tls/grafana.json @@ -0,0 +1,7 @@ +[ + { + "listen": ":3000", + "target": "127.0.0.1:3001", + "identities": [] + } +] diff --git a/infra/tls/loki.json b/infra/tls/loki.json new file mode 100644 index 0000000..3e3c729 --- /dev/null +++ b/infra/tls/loki.json @@ -0,0 +1,48 @@ +[ + { + "listen": ":3100", + "target": "127.0.0.1:3101", + "identities": [ + "collector", + "grafana", + "operator" + ], + "rules": [ + { + "identity": "collector", + "methods": [ + "POST" + ], + "prefixes": [ + "/otlp/v1/logs" + ] + }, + { + "identity": "grafana", + "methods": [ + "GET" + ], + "prefixes": [ + "/loki/api/v1/query", + "/loki/api/v1/label", + "/loki/api/v1/series", + "/loki/api/v1/index", + "/loki/api/v1/status/buildinfo" + ] + }, + { + "identity": "operator", + "methods": [ + "GET", + "POST", + "PUT", + "DELETE", + "HEAD" + ], + "prefixes": [ + "/" + ] + } + ] + } +] diff --git a/infra/tls/prometheus.json b/infra/tls/prometheus.json new file mode 100644 index 0000000..f361b2d --- /dev/null +++ b/infra/tls/prometheus.json @@ -0,0 +1,39 @@ +[ + { + "listen": ":9090", + "target": "127.0.0.1:9091", + "identities": [ + "grafana", + "operator" + ], + "rules": [ + { + "identity": "grafana", + "methods": [ + "GET", + "POST" + ], + "prefixes": [ + "/api/v1/query", + "/api/v1/label", + "/api/v1/series", + "/api/v1/metadata", + "/api/v1/status/buildinfo" + ] + }, + { + "identity": "operator", + "methods": [ + "GET", + "POST", + "PUT", + "DELETE", + "HEAD" + ], + "prefixes": [ + "/" + ] + } + ] + } +] diff --git a/infra/tls/s3.json b/infra/tls/s3.json new file mode 100644 index 0000000..c3a15f9 --- /dev/null +++ b/infra/tls/s3.json @@ -0,0 +1,12 @@ +[ + { + "listen": ":9000", + "target": "127.0.0.1:9001", + "identities": [ + "api", + "worker", + "housekeeping", + "operator" + ] + } +] diff --git a/infra/tls/tempo.json b/infra/tls/tempo.json new file mode 100644 index 0000000..b48cd45 --- /dev/null +++ b/infra/tls/tempo.json @@ -0,0 +1,53 @@ +[ + { + "listen": ":3200", + "target": "127.0.0.1:3201", + "identities": [ + "grafana", + "operator" + ], + "rules": [ + { + "identity": "grafana", + "methods": [ + "GET" + ], + "prefixes": [ + "/api/", + "/ready" + ] + }, + { + "identity": "operator", + "methods": [ + "GET", + "POST", + "PUT", + "DELETE", + "HEAD" + ], + "prefixes": [ + "/" + ] + } + ] + }, + { + "listen": ":4318", + "target": "127.0.0.1:4319", + "identities": [ + "collector" + ], + "rules": [ + { + "identity": "collector", + "methods": [ + "POST" + ], + "prefixes": [ + "/v1/traces" + ] + } + ] + } +] diff --git a/internal/database/database.go b/internal/database/database.go new file mode 100644 index 0000000..6c91a5c --- /dev/null +++ b/internal/database/database.go @@ -0,0 +1,108 @@ +package database + +import ( + "context" + "crypto/sha256" + "embed" + "fmt" + "github.com/jackc/pgx/v5/pgxpool" + "mtusi/messenger/internal/telemetry" + "os" + "sort" + "strconv" + "time" +) + +//go:embed migrations/*.sql +var migrations embed.FS + +func Open(ctx context.Context, url string) (*pgxpool.Pool, error) { + cfg, err := pgxpool.ParseConfig(url) + if err != nil { + return nil, fmt.Errorf("invalid database configuration") + } + if cfg.ConnConfig.TLSConfig == nil || cfg.ConnConfig.TLSConfig.InsecureSkipVerify || cfg.ConnConfig.TLSConfig.ServerName == "" || len(cfg.ConnConfig.Fallbacks) != 0 { + return nil, fmt.Errorf("database requires verified TLS without fallback") + } + cfg.MaxConns = 10 + if v := os.Getenv("DB_POOL_MAX"); v != "" { + n, e := strconv.Atoi(v) + if e != nil || n < 1 || n > 64 { + return nil, fmt.Errorf("DB_POOL_MAX must be 1..64") + } + cfg.MaxConns = int32(n) + } + cfg.ConnConfig.Tracer = telemetry.DBTracer{} + cfg.MinConns = 0 + cfg.MaxConnLifetime = 30 * time.Minute + cfg.MaxConnIdleTime = 5 * time.Minute + cfg.ConnConfig.ConnectTimeout = 2 * time.Second + cfg.ConnConfig.RuntimeParams["statement_timeout"] = "2000" + cfg.ConnConfig.RuntimeParams["lock_timeout"] = "1000" + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, fmt.Errorf("cannot create database pool") + } + if err = pool.Ping(ctx); err != nil { + pool.Close() + return nil, fmt.Errorf("database unavailable") + } + return pool, nil +} + +// All migrations and the version ledger commit together. An advisory lock also +// serializes bootstrap across API instances; edited applied migrations fail. +func Migrate(ctx context.Context, pool *pgxpool.Pool) error { + tx, err := pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(context.Background()) + if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(2026002)"); err != nil { + return err + } + if _, err = tx.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())`); err != nil { + return err + } + entries, err := migrations.ReadDir("migrations") + if err != nil { + return err + } + sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() }) + for _, entry := range entries { + body, err := migrations.ReadFile("migrations/" + entry.Name()) + if err != nil { + return err + } + checksum := fmt.Sprintf("%x", sha256.Sum256(body)) + var stored string + rows, err := tx.Query(ctx, "SELECT checksum FROM schema_migrations WHERE version=$1", entry.Name()) + if err != nil { + return err + } + found := rows.Next() + if found { + err = rows.Scan(&stored) + } + if err == nil { + err = rows.Err() + } + rows.Close() + if err != nil { + return err + } + if found { + if stored != checksum { + return fmt.Errorf("applied migration changed: %s", entry.Name()) + } + continue + } + if _, err = tx.Exec(ctx, string(body)); err != nil { + return err + } + if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version,checksum) VALUES($1,$2)", entry.Name(), checksum); err != nil { + return err + } + } + return tx.Commit(ctx) +} diff --git a/internal/database/migrations/001_initial.sql b/internal/database/migrations/001_initial.sql new file mode 100644 index 0000000..005476d --- /dev/null +++ b/internal/database/migrations/001_initial.sql @@ -0,0 +1,36 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + last_message_at timestamptz NOT NULL DEFAULT '-infinity' +); +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id), + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members(user_id, chat_id); +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL, + text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), + created_at timestamptz NOT NULL, + FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id) +); +CREATE INDEX messages_history_idx ON messages(chat_id, created_at, id); +CREATE INDEX chats_order_idx ON chats(created_at, id); +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32), + user_id uuid NOT NULL REFERENCES users(id), + expires_at timestamptz NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX sessions_expiry_idx ON sessions(expires_at); diff --git a/internal/database/migrations/002_idempotency.sql b/internal/database/migrations/002_idempotency.sql new file mode 100644 index 0000000..23cfaeb --- /dev/null +++ b/internal/database/migrations/002_idempotency.sql @@ -0,0 +1,10 @@ +CREATE TABLE message_requests ( + user_id uuid NOT NULL REFERENCES users(id), + chat_id uuid NOT NULL REFERENCES chats(id), + key text NOT NULL, + body_hash bytea NOT NULL, + response jsonb NOT NULL, + expires_at timestamptz NOT NULL, + PRIMARY KEY(user_id,chat_id,key) +); +CREATE INDEX message_requests_expiry_idx ON message_requests(expires_at); diff --git a/internal/database/migrations/003_attachments.sql b/internal/database/migrations/003_attachments.sql new file mode 100644 index 0000000..f55c2a2 --- /dev/null +++ b/internal/database/migrations/003_attachments.sql @@ -0,0 +1,29 @@ +ALTER TABLE messages DROP CONSTRAINT messages_text_check; +ALTER TABLE messages ADD CHECK(char_length(text) BETWEEN 0 AND 4000); +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + owner_id uuid NOT NULL REFERENCES users(id), + filename text NOT NULL, + object_key text NOT NULL UNIQUE, + content_type text NOT NULL CHECK(content_type IN ('image/png','image/jpeg')), + size_bytes bigint NOT NULL CHECK(size_bytes BETWEEN 1 AND 10485760), + sha256 text NOT NULL CHECK(sha256 ~ '^[a-f0-9]{64}$'), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE message_attachments ( + message_id uuid NOT NULL REFERENCES messages(id), + attachment_id uuid NOT NULL REFERENCES attachments(id), + position integer NOT NULL CHECK(position BETWEEN 0 AND 9), + PRIMARY KEY(message_id,attachment_id), + UNIQUE(message_id,position) +); +-- Durable upload journal is committed BEFORE PUT, so incomplete work remains +-- attributable after process termination. Final metadata + journal deletion +-- share one PG transaction, under the same per-key lock as the reconciler. +CREATE TABLE upload_intents ( + object_key text PRIMARY KEY, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX attachments_chat_idx ON attachments(chat_id); diff --git a/internal/database/migrations/004_pipeline.sql b/internal/database/migrations/004_pipeline.sql new file mode 100644 index 0000000..fa55d1e --- /dev/null +++ b/internal/database/migrations/004_pipeline.sql @@ -0,0 +1,30 @@ +ALTER TABLE attachments ADD COLUMN status text NOT NULL DEFAULT 'ready' CHECK(status IN ('queued','processing','ready','failed')); +ALTER TABLE attachments ADD COLUMN error_code text; +ALTER TABLE attachments ADD COLUMN variants jsonb NOT NULL DEFAULT '[]'; +ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1 CHECK(pipeline_version>0); +ALTER TABLE attachments ADD COLUMN staging_key text; +CREATE TABLE pipeline_jobs ( + job_id uuid PRIMARY KEY, + attachment_id uuid NOT NULL REFERENCES attachments(id), + pipeline_version integer NOT NULL CHECK(pipeline_version>0), + attempt integer NOT NULL DEFAULT 0, + lease_token uuid, + lease_until timestamptz, + next_attempt_at timestamptz NOT NULL DEFAULT clock_timestamp(), + published_at timestamptz, + finished_at timestamptz, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + traceparent text NOT NULL DEFAULT '', + tracestate text NOT NULL DEFAULT '', + UNIQUE(attachment_id,pipeline_version) +); +CREATE INDEX pipeline_dispatch_idx ON pipeline_jobs(next_attempt_at) WHERE finished_at IS NULL; +CREATE TABLE pipeline_audit ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + job_id uuid NOT NULL REFERENCES pipeline_jobs(job_id), + event text NOT NULL, + attempt integer NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +-- This is the durable, queryable failed registry (DLQ equivalent). +CREATE VIEW failed_jobs AS SELECT j.job_id,j.attachment_id,j.pipeline_version,j.attempt,a.error_code,j.finished_at FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version WHERE a.status='failed'; diff --git a/internal/database/migrations/005_observability.sql b/internal/database/migrations/005_observability.sql new file mode 100644 index 0000000..9958674 --- /dev/null +++ b/internal/database/migrations/005_observability.sql @@ -0,0 +1,2 @@ +ALTER TABLE pipeline_jobs ADD COLUMN ready_at timestamptz; +CREATE INDEX pipeline_jobs_created_idx ON pipeline_jobs(created_at); diff --git a/internal/database/migrations/006_auth_limits.sql b/internal/database/migrations/006_auth_limits.sql new file mode 100644 index 0000000..abea8b4 --- /dev/null +++ b/internal/database/migrations/006_auth_limits.sql @@ -0,0 +1,12 @@ +CREATE TABLE auth_limits (bucket text NOT NULL, window_id bigint NOT NULL, count integer NOT NULL, PRIMARY KEY(bucket,window_id)); +-- Both counters increment in one transaction, global key locked first. +CREATE FUNCTION auth_admit(subject text) RETURNS boolean LANGUAGE plpgsql AS $$ +DECLARE win bigint; total integer; per_subject integer; +BEGIN + win := floor(extract(epoch from clock_timestamp()) / 60); + INSERT INTO auth_limits VALUES ('global',win,1) ON CONFLICT(bucket,window_id) DO UPDATE SET count=auth_limits.count+1 RETURNING count INTO total; + IF total>120 THEN RETURN false; END IF; + INSERT INTO auth_limits VALUES (subject,win,1) ON CONFLICT(bucket,window_id) DO UPDATE SET count=auth_limits.count+1 RETURNING count INTO per_subject; + DELETE FROM auth_limits WHERE window_id maxUpload { + _, _ = io.Copy(io.Discard, io.LimitReader(r.Body, maxUpload+1)) + fail(w, 413, "payload_too_large", "Maximum upload is 10 MiB") + return + } + select { + case s.uploads <- struct{}{}: + defer func() { <-s.uploads }() + case <-r.Context().Done(): + unavailable(w) + return + } + f, e := os.CreateTemp("", "messenger-upload-*") + if e != nil { + unavailable(w) + return + } + defer os.Remove(f.Name()) + defer f.Close() + hash := sha256.New() + n, e := io.Copy(io.MultiWriter(f, hash), http.MaxBytesReader(w, r.Body, maxUpload)) + if e != nil { + var over *http.MaxBytesError + if errors.As(e, &over) { + fail(w, 413, "payload_too_large", "Maximum upload is 10 MiB") + } else { + bad(w) + } + return + } + _, _ = f.Seek(0, io.SeekStart) + config, format, e := image.DecodeConfig(f) + if e != nil || "image/"+format != contentType { + fail(w, 415, "unsupported_media_type", "Invalid image or MIME mismatch") + return + } + if config.Width < 1 || config.Height < 1 || int64(config.Width)*int64(config.Height) > maxPixels { + fail(w, 413, "payload_too_large", "Maximum image is 40 million pixels") + return + } + _, _ = f.Seek(0, io.SeekStart) + if !validateImage(f) { + fail(w, 415, "unsupported_media_type", "Invalid image") + return + } + _, _ = f.Seek(0, io.SeekStart) + id := uuid() + key := "staging/" + id + ctx := r.Context() + // Journal survives a crash between PUT and metadata COMMIT. + if _, e = s.db.Exec(ctx, "INSERT INTO upload_intents(object_key) VALUES($1)", key); e != nil { + unavailable(w) + return + } + tx, e := s.db.Begin(ctx) + if e != nil { + unavailable(w) + return + } + defer tx.Rollback(context.Background()) + if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,4))", key); e != nil { + unavailable(w) + return + } + // Disable multipart: the bounded spool is <=10MiB, hence one atomic object PUT. + _, e = s.objects.Client.PutObject(ctx, s.objects.Bucket, key, f, n, minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true}) + if e != nil { + unavailable(w) + return + } + a, _, e := scanAttachment(tx.QueryRow(ctx, `INSERT INTO attachments AS a(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,status,staging_key) VALUES($1,$2,$3,$4,$5,$6,$7,$8,'queued',$9) RETURNING `+attachmentColumns, id, cid, uid, q.Get("filename"), "originals/"+id+"/v1/original", contentType, n, hex.EncodeToString(hash.Sum(nil)), key)) + if e != nil { + unavailable(w) + return + } + // Admission and intent share a transaction; no unbounded accepted backlog. + if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(2026005)"); e != nil { + unavailable(w) + return + } + var pending int + if e = tx.QueryRow(ctx, "SELECT count(*) FROM pipeline_jobs WHERE finished_at IS NULL").Scan(&pending); e != nil { + unavailable(w) + return + } + if pending >= 1000 { + w.Header().Set("Retry-After", "5") + fail(w, 429, "rate_limited", "Processing backlog is full") + return + } + parent, state := telemetry.Inject(ctx) + if _, e = tx.Exec(ctx, `INSERT INTO pipeline_jobs(job_id,attachment_id,pipeline_version,traceparent,tracestate) VALUES($1,$2,1,$3,$4)`, uuid(), id, parent, state); e != nil { + unavailable(w) + return + } + if _, e = tx.Exec(ctx, "DELETE FROM upload_intents WHERE object_key=$1", key); e != nil { + unavailable(w) + return + } + if tx.Commit(ctx) != nil { + unavailable(w) + return + } + reply(w, 202, a) +} +func validateImage(r io.Reader) bool { _, _, e := image.Decode(r); return e == nil } + +func (s *Server) serveAttachment(w http.ResponseWriter, r *http.Request, uid string, parts []string) { + if r.Method != "GET" || (len(parts) != 4 && len(parts) != 5) || (len(parts) == 5 && parts[4] != "content") { + missing(w) + return + } + id := strings.ToLower(parts[3]) + if !uuidRE.MatchString(id) { + bad(w) + return + } + a, key, e := scanAttachment(s.db.QueryRow(r.Context(), `SELECT `+attachmentColumns+` FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id AND m.user_id=$2 WHERE a.id=$1`, id, uid)) + if errors.Is(e, pgx.ErrNoRows) { + missing(w) + return + } + if e != nil { + unavailable(w) + return + } + if len(parts) == 4 { + reply(w, 200, a) + return + } + q, e := url.ParseQuery(r.URL.RawQuery) + if e != nil || len(q["variant"]) > 1 { + bad(w) + return + } + if a.Status != "ready" { + fail(w, 409, "conflict", "Attachment is not ready") + return + } + variant := q.Get("variant") + if variant != "" && variant != "original" { + found := false + for _, v := range a.Variants { + if v.Name == variant { + a.ContentType = v.ContentType + a.Size = v.Size + key = strings.TrimSuffix(key, "original") + variant + found = true + break + } + } + if !found { + missing(w) + return + } + } + object, e := s.objects.Client.GetObject(r.Context(), s.objects.Bucket, key, minio.GetObjectOptions{}) + if e != nil { + unavailable(w) + return + } + defer object.Close() + info, e := object.Stat() + if e != nil || info.Size != a.Size { + unavailable(w) + return + } + w.Header().Set("Content-Type", a.ContentType) + w.Header().Set("Content-Length", fmt.Sprint(a.Size)) + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename})) + w.WriteHeader(200) + _, _ = io.Copy(w, object) +} + +// Normalize optional attachments before hashing; JSON key ordering is irrelevant. +func parseMessage(w http.ResponseWriter, r *http.Request) (string, []string, bool) { + var in struct { + Text *string `json:"text"` + Attachments []string `json:"attachment_ids"` + } + // strict decoder accepts an explicitly optional field (suffix '?'). + if !decode(w, r, &in, "text", "attachment_ids?") { + return "", nil, false + } + if in.Text == nil || !utf8.ValidString(*in.Text) || utf8.RuneCountInString(*in.Text) > 4000 || len(in.Attachments) > 10 || (strings.TrimSpace(*in.Text) == "" && len(in.Attachments) == 0) { + bad(w) + return "", nil, false + } + seen := map[string]bool{} + for i, id := range in.Attachments { + id = strings.ToLower(id) + if !uuidRE.MatchString(id) || seen[id] { + bad(w) + return "", nil, false + } + seen[id] = true + in.Attachments[i] = id + } + if in.Attachments == nil { + in.Attachments = []string{} + } + return *in.Text, in.Attachments, true +} diff --git a/internal/messenger/auth_limit.go b/internal/messenger/auth_limit.go new file mode 100644 index 0000000..dff159b --- /dev/null +++ b/internal/messenger/auth_limit.go @@ -0,0 +1,24 @@ +package messenger + +import ( + "crypto/sha256" + "fmt" + "net/http" +) + +// Shared PG counters, not per-process memory or untrusted forwarding headers. +// Unknown and known usernames use the same hash/bucket and admission rules. +func (s *Server) admitAuth(w http.ResponseWriter, r *http.Request, username string) bool { + key := fmt.Sprintf("%x", sha256.Sum256([]byte(username))) + var allowed bool + if e := s.db.QueryRow(r.Context(), "SELECT auth_admit($1)", key).Scan(&allowed); e != nil { + unavailable(w) + return false + } + if !allowed { + w.Header().Set("Retry-After", "60") + fail(w, 429, "rate_limited", "Authentication rate limit exceeded") + return false + } + return true +} diff --git a/internal/messenger/child_linux.go b/internal/messenger/child_linux.go new file mode 100644 index 0000000..dadf05b --- /dev/null +++ b/internal/messenger/child_linux.go @@ -0,0 +1,18 @@ +//go:build linux + +package messenger + +import ( + "os/exec" + "syscall" +) + +func configureChild(cmd *exec.Cmd) { + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { + if cmd.Process != nil { + return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + } + return nil + } +} diff --git a/internal/messenger/child_other.go b/internal/messenger/child_other.go new file mode 100644 index 0000000..05b2534 --- /dev/null +++ b/internal/messenger/child_other.go @@ -0,0 +1,7 @@ +//go:build !linux + +package messenger + +import "os/exec" + +func configureChild(cmd *exec.Cmd) {} diff --git a/internal/messenger/database_test.go b/internal/messenger/database_test.go new file mode 100644 index 0000000..8806e4d --- /dev/null +++ b/internal/messenger/database_test.go @@ -0,0 +1,163 @@ +package messenger + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "mtusi/messenger/internal/database" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + "time" +) + +// Real PostgreSQL + HTTP + the race detector, in the optional Compose tests +// service. Local go test skips this test unless the DB secret path is supplied. +func TestDatabaseConcurrentHTTP(t *testing.T) { + path := os.Getenv("DATABASE_TEST_URL_FILE") + if path == "" { + t.Skip("run make test-race for real PostgreSQL HTTP integration") + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + pool, err := database.Open(ctx, strings.TrimSpace(string(raw))) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + if err = database.Migrate(ctx, pool); err != nil { + t.Fatal(err) + } + api := New(pool, nil, make([]byte, 32), 3600, nil) + ts := httptest.NewServer(api) + defer ts.Close() + call := func(method, path, body, auth string, status int) map[string]any { + t.Helper() + r, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body)) + if err != nil { + t.Error(err) + return nil + } + if body != "" { + r.Header.Set("Content-Type", "application/json") + } + r.Header.Set("Authorization", auth) + if method == "POST" && strings.HasSuffix(path, "/messages") { + r.Header.Set("Idempotency-Key", uuid()) + } + response, err := ts.Client().Do(r) + if err != nil { + t.Error(err) + return nil + } + defer response.Body.Close() + b, err := io.ReadAll(response.Body) + if err != nil { + t.Error(err) + return nil + } + if response.StatusCode != status { + t.Errorf("%s %s: want %d got %d", method, path, status, response.StatusCode) + return nil + } + var v map[string]any + if err = json.Unmarshal(b, &v); err != nil { + t.Error(err) + } + return v + } + username := "go_" + strings.ReplaceAll(uuid(), "-", "")[:20] + user := call("POST", "/api/v1/users", fmt.Sprintf(`{"username":%q,"display_name":"Race","password":"Synthetic-Go-Test-123"}`, username), "", 201) + if user == nil { + t.Fatal("create failed") + } + basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":Synthetic-Go-Test-123")) + session := call("POST", "/api/v1/auth/sessions", "", basic, 201) + if session == nil { + t.Fatal("login failed") + } + bearer := "Bearer " + session["token"].(string) + chat := call("POST", "/api/v1/chats", fmt.Sprintf(`{"title":"Race","member_ids":[%q]}`, user["id"]), bearer, 201) + if chat == nil { + t.Fatal("chat failed") + } + messages := "/api/v1/chats/" + chat["id"].(string) + "/messages" + var wg sync.WaitGroup + for worker := 0; worker < 10; worker++ { + wg.Add(1) + go func(worker int) { + defer wg.Done() + for j := 0; j < 10; j++ { + call("POST", messages, fmt.Sprintf(`{"text":"worker-%d-message-%d"}`, worker, j), bearer, 201) + } + }(worker) + } + wg.Wait() + page := call("GET", messages+"?limit=100", "", bearer, 200) + if page == nil { + t.Fatal("history failed") + } + items := page["items"].([]any) + if len(items) != 100 { + t.Fatalf("expected 100 messages, got %d", len(items)) + } + seen := map[string]bool{} + for _, v := range items { + m := v.(map[string]any) + id := m["id"].(string) + if seen[id] { + t.Fatal("duplicate ID") + } + seen[id] = true + } + // Race a single key through the real server, then verify only one side effect. + var repeatWG sync.WaitGroup + ids := make(chan string, 12) + for i := 0; i < 12; i++ { + repeatWG.Add(1) + go func() { + defer repeatWG.Done() + req, _ := http.NewRequest("POST", ts.URL+messages, strings.NewReader(`{"text":"one key"}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", bearer) + req.Header.Set("Idempotency-Key", "same-concurrent-key") + res, err := ts.Client().Do(req) + if err != nil { + t.Error(err) + return + } + defer res.Body.Close() + var m Message + if res.StatusCode != 201 || json.NewDecoder(res.Body).Decode(&m) != nil { + t.Error("repeat failed") + return + } + ids <- m.ID + }() + } + repeatWG.Wait() + close(ids) + var expected string + for id := range ids { + if expected == "" { + expected = id + } + if id != expected { + t.Error("idempotency duplicate") + } + } + var count int + if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM messages WHERE chat_id=$1", chat["id"]).Scan(&count); err != nil || count != 101 { + t.Errorf("want 101 persisted messages, got %d: %v", count, err) + } + t.Log("100 confirmed messages from 10 clients through real HTTP and PostgreSQL; race detector enabled") +} diff --git a/internal/messenger/operator.go b/internal/messenger/operator.go new file mode 100644 index 0000000..afca64b --- /dev/null +++ b/internal/messenger/operator.go @@ -0,0 +1,137 @@ +package messenger + +import ( + "context" + "errors" + "fmt" + "github.com/jackc/pgx/v5" + "github.com/minio/minio-go/v7" + "strings" + "time" +) + +// Operator-only CLI. It exposes no unauthenticated HTTP mutation endpoint. +func (p *Pipeline) Replay(ctx context.Context, id string, newVersion bool) error { + if !uuidRE.MatchString(id) { + return fmt.Errorf("expected attachment UUID") + } + tx, e := p.DB.Begin(ctx) + if e != nil { + return e + } + defer tx.Rollback(context.Background()) + var status, key, stage string + var version int + e = tx.QueryRow(ctx, `SELECT status,object_key,COALESCE(staging_key,''),pipeline_version FROM attachments WHERE id=$1 FOR UPDATE`, id).Scan(&status, &key, &stage, &version) + if e != nil { + return e + } + if newVersion { + if status != "ready" && status != "queued" && status != "processing" { + return fmt.Errorf("replay failed before version upgrade") + } + if version >= 2 { + return fmt.Errorf("supported pipeline versions: 1 and 2") + } + version++ + if status == "ready" { + stage = key + } + } else { + if status != "failed" { + return fmt.Errorf("only failed can be replayed") + } + } + if _, e = p.Objects.Client.StatObject(ctx, p.Objects.Bucket, stage, minio.StatObjectOptions{}); e != nil { + return fmt.Errorf("source unavailable; restore before replay") + } + var jobID string + if newVersion { + jobID = uuid() + if _, e = tx.Exec(ctx, "UPDATE pipeline_jobs SET finished_at=clock_timestamp() WHERE attachment_id=$1 AND finished_at IS NULL", id); e != nil { + return e + } + _, e = tx.Exec(ctx, `INSERT INTO pipeline_jobs(job_id,attachment_id,pipeline_version) VALUES($1,$2,$3)`, jobID, id, version) + } else { + e = tx.QueryRow(ctx, `UPDATE pipeline_jobs SET attempt=0,lease_token=NULL,lease_until=NULL,published_at=NULL,finished_at=NULL,next_attempt_at=clock_timestamp() WHERE attachment_id=$1 AND pipeline_version=$2 RETURNING job_id::text`, id, version).Scan(&jobID) + } + if e != nil { + return e + } + _, e = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,variants='[]',pipeline_version=$2,staging_key=$3,updated_at=clock_timestamp() WHERE id=$1`, id, version, stage) + if e != nil { + return e + } + event := "operator_replay" + if newVersion { + event = "operator_new_version" + } + if _, e = tx.Exec(ctx, `INSERT INTO pipeline_audit(job_id,event,attempt) VALUES($1,$2,0)`, jobID, event); e != nil { + return e + } + return tx.Commit(ctx) +} + +// Only staging is collected automatically. Live queued/processing work and final +// objects are always protected. Ready stage is redundant; failed source has 7d +// retention. Unattributed aborted uploads/intents have a conservative 24h grace. +func (p *Pipeline) Cleanup(ctx context.Context, apply bool) error { + for object := range p.Objects.Client.ListObjects(ctx, p.Objects.Bucket, minio.ListObjectsOptions{Prefix: "staging/", Recursive: true}) { + if object.Err != nil { + return object.Err + } + if time.Since(object.LastModified) < 24*time.Hour { + continue + } + tx, e := p.DB.Begin(ctx) + if e != nil { + return e + } + if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,4))", object.Key); e != nil { + tx.Rollback(ctx) + return e + } + var status string + var updated time.Time + e = tx.QueryRow(ctx, `SELECT status,updated_at FROM attachments WHERE staging_key=$1 FOR UPDATE`, object.Key).Scan(&status, &updated) + if e != nil && !errors.Is(e, pgx.ErrNoRows) { + tx.Rollback(ctx) + return e + } + safe := errors.Is(e, pgx.ErrNoRows) || status == "ready" || (status == "failed" && time.Since(updated) > 7*24*time.Hour) + if safe { + p.Log.Info("staging_cleanup", "event", "staging_cleanup", "apply", apply, "status", status) + if apply { + if e = p.Objects.Client.RemoveObject(ctx, p.Objects.Bucket, object.Key, minio.RemoveObjectOptions{}); e != nil { + tx.Rollback(ctx) + return e + } + if _, e = tx.Exec(ctx, `DELETE FROM upload_intents WHERE object_key=$1`, object.Key); e != nil { + tx.Rollback(ctx) + return e + } + } + } + if e = tx.Commit(ctx); e != nil { + return e + } + } + return nil +} +func (p *Pipeline) RunHousekeeping(ctx context.Context) error { + for ctx.Err() == nil { + if e := p.Cleanup(ctx, true); e != nil { + p.Log.Warn("cleanup_retry", "event", "cleanup_retry") + } + if !wait(ctx, time.Hour) { + break + } + } + return nil +} +func ParseOperatorArgs(args []string) (string, bool, error) { + if len(args) != 1 || strings.TrimSpace(args[0]) == "" { + return "", false, fmt.Errorf("expected one attachment UUID") + } + return args[0], false, nil +} diff --git a/internal/messenger/password.go b/internal/messenger/password.go new file mode 100644 index 0000000..657c745 --- /dev/null +++ b/internal/messenger/password.go @@ -0,0 +1,42 @@ +package messenger + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "fmt" + "golang.org/x/crypto/argon2" + "strings" +) + +// Fixed, bounded parameters: 64 MiB, 3 passes, 2 lanes, 16-byte salt, +// 32-byte result. The HTTP layer bounds simultaneous KDF work to 2 calls. +func hashPassword(password string) string { + salt := make([]byte, 16) + if _, err := rand.Read(salt); err != nil { + panic(err) + } + hash := argon2.IDKey([]byte(password), salt, 3, 64*1024, 2, 32) + return "$argon2id$v=19$m=65536,t=3,p=2$" + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash) +} +func verifyPassword(password, encoded string) bool { + parts := strings.Split(encoded, "$") + if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" { + return false + } + var memory, passes, lanes uint32 + if n, e := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &passes, &lanes); e != nil || n != 3 || parts[3] != fmt.Sprintf("m=%d,t=%d,p=%d", memory, passes, lanes) || memory < 8192 || memory > 65536 || passes < 1 || passes > 3 || lanes < 1 || lanes > 2 { + return false + } + salt, e1 := base64.RawStdEncoding.DecodeString(parts[4]) + want, e2 := base64.RawStdEncoding.DecodeString(parts[5]) + if e1 != nil || e2 != nil || len(salt) != 16 || len(want) != 32 { + return false + } + got := argon2.IDKey([]byte(password), salt, passes, memory, uint8(lanes), 32) + return subtle.ConstantTimeCompare(got, want) == 1 +} + +func needsRehash(hash string) bool { + return !strings.HasPrefix(hash, "$argon2id$v=19$m=65536,t=3,p=2$") +} diff --git a/internal/messenger/password_test.go b/internal/messenger/password_test.go new file mode 100644 index 0000000..a24a668 --- /dev/null +++ b/internal/messenger/password_test.go @@ -0,0 +1,20 @@ +package messenger + +import ( + "strings" + "testing" +) + +func TestPasswordFullUnicodeRange(t *testing.T) { + password := strings.Repeat("🙂", 128) // 512 bytes: exceeds bcrypt's 72-byte limit. + hash := hashPassword(password) + if !verifyPassword(password, hash) || verifyPassword(password+"x", hash) { + t.Fatal("password mismatch") + } + if hash == hashPassword(password) { + t.Fatal("salt reused") + } + if verifyPassword(password, "$argon2id$v=19$m=999999999,t=3,p=2$abc$def") { + t.Fatal("unbounded parameters accepted") + } +} diff --git a/internal/messenger/pipeline.go b/internal/messenger/pipeline.go new file mode 100644 index 0000000..96a22eb --- /dev/null +++ b/internal/messenger/pipeline.go @@ -0,0 +1,441 @@ +package messenger + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/minio/minio-go/v7" + "github.com/redis/go-redis/v9" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/trace" + "io" + "log/slog" + "math/rand/v2" + "mtusi/messenger/internal/telemetry" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "time" +) + +const stream = "attachment.jobs.v1" +const group = "image-workers" +const maxAttempts = 5 +const leaseSeconds = 45 + +type Job struct { + SchemaVersion int `json:"schema_version"` + ID string `json:"job_id"` + Type string `json:"type"` + AttachmentID string `json:"attachment_id"` + Version int `json:"pipeline_version"` + Attempt int `json:"attempt"` + CreatedAt string `json:"created_at"` + Traceparent string `json:"traceparent,omitempty"` + Tracestate string `json:"tracestate,omitempty"` +} +type Pipeline struct { + DB *pgxpool.Pool + Broker *redis.Client + Objects *ObjectStore + Log *slog.Logger +} + +func NewPipeline(db *pgxpool.Pool, broker *redis.Client, o *ObjectStore, log *slog.Logger) *Pipeline { + return &Pipeline{db, broker, o, log} +} +func wait(ctx context.Context, d time.Duration) bool { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return false + case <-t.C: + return true + } +} +func (p *Pipeline) RunDispatcher(ctx context.Context) error { + for ctx.Err() == nil { + if e := p.dispatch(ctx); e != nil { + p.Log.Warn("outbox_retry", "event", "outbox_retry") + } + if !wait(ctx, 500*time.Millisecond) { + break + } + } + return nil +} +func (p *Pipeline) dispatch(ctx context.Context) error { + // Small per-row transaction + SKIP LOCKED allows multiple dispatchers. A crash + // after XADD before COMMIT gives a duplicate, never a missing durable intent. + for i := 0; i < 32; i++ { + tx, e := p.DB.Begin(ctx) + if e != nil { + return e + } + var j Job + var created time.Time + e = tx.QueryRow(ctx, `SELECT job_id::text,attachment_id::text,pipeline_version,attempt+1,created_at,traceparent,tracestate FROM pipeline_jobs WHERE finished_at IS NULL AND next_attempt_at<=clock_timestamp() AND (lease_until IS NULL OR lease_until 4 { + return fmt.Errorf("WORKER_CONCURRENCY must be 1..4") + } + for ctx.Err() == nil { + e := p.Broker.XGroupCreateMkStream(ctx, stream, group, "0").Err() + if e == nil || strings.Contains(e.Error(), "BUSYGROUP") { + break + } + if !wait(ctx, time.Second) { + return nil + } + } + telemetry.WorkerCapacity(concurrency) + var wg sync.WaitGroup + for i := 0; i < concurrency; i++ { + wg.Add(1) + go func() { defer wg.Done(); p.consume(ctx, uuid()) }() + } + wg.Wait() + return nil +} +func (p *Pipeline) consume(ctx context.Context, consumer string) { + cursor := "0-0" + for ctx.Err() == nil { + claimed, next, e := p.Broker.XAutoClaim(ctx, &redis.XAutoClaimArgs{Stream: stream, Group: group, Consumer: consumer, MinIdle: time.Minute, Start: cursor, Count: 1}).Result() + cursor = next + if e == nil && len(claimed) > 0 { + p.handle(ctx, claimed[0]) + continue + } + entries, e := p.Broker.XReadGroup(ctx, &redis.XReadGroupArgs{Group: group, Consumer: consumer, Streams: []string{stream, ">"}, Count: 1, Block: time.Second}).Result() + if e != nil { + if e != redis.Nil { + wait(ctx, time.Second) + } + continue + } + for _, entry := range entries { + for _, m := range entry.Messages { + p.handle(ctx, m) + } + } + } +} +func (p *Pipeline) handle(ctx context.Context, m redis.XMessage) { + raw, _ := m.Values["payload"].(string) + var j Job + d := json.NewDecoder(strings.NewReader(raw)) + d.DisallowUnknownFields() + if len(raw) > 4096 || d.Decode(&j) != nil || j.SchemaVersion != 1 || j.Type != "attachment.process.v1" || !uuidRE.MatchString(j.ID) || !uuidRE.MatchString(j.AttachmentID) || j.Version < 1 || j.Attempt < 1 { + p.Log.Warn("invalid_job", "event", "invalid_job") + p.ack(ctx, m.ID) + return + } + // The authoritative attempt and storage locations come from PostgreSQL, never + // from untrusted broker payload fields. A terminal/stale delivery is a no-op. + ctx, span := telemetry.Start(telemetry.Extract(ctx, j.Traceparent, j.Tracestate), "queue.consume", trace.SpanKindConsumer) + defer span.End() + done, e := p.process(ctx, j) + telemetry.Failure(span, e) + if e != nil { + p.Log.WarnContext(ctx, "job_deferred", "event", "job_deferred", "job_id", j.ID) + } + if done { + p.ack(ctx, m.ID) + } +} +func (p *Pipeline) ack(ctx context.Context, id string) { + // Do not delete an entry unless ACK succeeded; the only consumer group is ours. + if p.Broker.XAck(ctx, stream, group, id).Err() == nil { + p.Broker.XDel(ctx, stream, id) + } +} +func (p *Pipeline) process(parent context.Context, j Job) (bool, error) { + ctx, cancel := context.WithTimeout(parent, 30*time.Second) + defer cancel() + tx, e := p.DB.Begin(ctx) + if e != nil { + return false, e + } + defer tx.Rollback(context.Background()) + var status, key, sha, contentType string + var version, attempt int + var size int64 + var lease *time.Time + e = tx.QueryRow(ctx, `SELECT a.status,a.pipeline_version,a.staging_key,a.sha256,a.content_type,a.size_bytes,j.attempt,j.lease_until FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=$1 AND j.attachment_id=$2 AND j.pipeline_version=$3 FOR UPDATE OF j,a`, j.ID, j.AttachmentID, j.Version).Scan(&status, &version, &key, &sha, &contentType, &size, &attempt, &lease) + if errors.Is(e, pgx.ErrNoRows) { + return true, nil + } + if e != nil { + return false, e + } + if version != j.Version || status == "ready" || status == "failed" { + return true, nil + } + var now time.Time + if e = tx.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); e != nil { + return false, e + } + if lease != nil && lease.After(now) { + return true, nil + } // live attempt; DB recovery remains durable + if attempt >= maxAttempts { + _, e = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=$1;`, j.AttachmentID) + if e == nil { + _, e = tx.Exec(ctx, "UPDATE pipeline_jobs SET finished_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1", j.ID) + } + if e != nil { + return false, e + } + return true, tx.Commit(ctx) + } + token := uuid() + attempt++ + if _, e = tx.Exec(ctx, `UPDATE pipeline_jobs SET attempt=$2,lease_token=$3,lease_until=clock_timestamp()+interval '45 seconds' WHERE job_id=$1`, j.ID, attempt, token); e != nil { + return false, e + } + if _, e = tx.Exec(ctx, `UPDATE attachments SET status='processing',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID); e != nil { + return false, e + } + if _, e = tx.Exec(ctx, `INSERT INTO pipeline_audit(job_id,event,attempt) VALUES($1,'claimed',$2)`, j.ID, attempt); e != nil { + return false, e + } + if e = tx.Commit(ctx); e != nil { + return false, e + } + trace.SpanFromContext(ctx).SetAttributes(attribute.Int("job.attempt", attempt), attribute.Int("pipeline.version", j.Version)) + attemptStart := time.Now() + outcome := "failure" + defer func() { + trace.SpanFromContext(ctx).SetAttributes(attribute.String("job.outcome", outcome)) + telemetry.Job(ctx, outcome, time.Since(attemptStart).Seconds()) + }() + p.Log.InfoContext(ctx, "job_started", "event", "job_started", "job_id", j.ID, "attempt", attempt, "pipeline_version", j.Version) + faultPoint("before_objects") + telemetry.Busy.Add(1) + variants, processErr := p.perform(ctx, j, key, sha, contentType, size) + telemetry.Busy.Add(-1) + telemetry.Failure(trace.SpanFromContext(ctx), processErr) + if processErr == nil { + faultPoint("after_objects") + } + // A short independent commit budget allows recording a timed-out attempt; + // a cancelled/killed process instead recovers via the persisted lease. + finish, stop := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) + defer stop() + tx, e = p.DB.Begin(finish) + if e != nil { + return false, e + } + defer tx.Rollback(context.Background()) + var currentToken *string + var currentVersion int + e = tx.QueryRow(finish, `SELECT j.lease_token::text,a.pipeline_version FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=$1 FOR UPDATE OF j,a`, j.ID).Scan(¤tToken, ¤tVersion) + if e != nil { + return false, e + } + if currentToken == nil || *currentToken != token || currentVersion != j.Version { + return true, nil + } + if processErr == nil { + encoded, _ := json.Marshal(variants) + _, e = tx.Exec(finish, `UPDATE attachments SET status='ready',error_code=NULL,variants=$2,object_key=$3,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID, encoded, resultPrefix(j)+"original") + if e == nil { + _, e = tx.Exec(finish, `UPDATE pipeline_jobs SET finished_at=clock_timestamp(),ready_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1`, j.ID) + } + } else { + permanent := errors.Is(processErr, errInvalidImage) + if permanent || attempt >= maxAttempts { + code := "retry_exhausted" + if permanent { + code = "invalid_image" + } + _, e = tx.Exec(finish, `UPDATE attachments SET status='failed',error_code=$2,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID, code) + if e == nil { + _, e = tx.Exec(finish, `UPDATE pipeline_jobs SET finished_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1`, j.ID) + } + } else { + _, e = tx.Exec(finish, `UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID) + delay := time.Duration(1< maxUpload { + return 1 + } + if string(h[4:]) == "eXIf" { + b := make([]byte, n) + if _, e = io.ReadFull(f, b); e != nil { + return 1 + } + return tiffOrientation(b) + } + if string(h[4:]) == "IEND" { + return 1 + } + if _, e = f.Seek(int64(n)+4, io.SeekCurrent); e != nil { + return 1 + } + } +} +func tiffOrientation(b []byte) int { + if len(b) < 8 { + return 1 + } + var order binary.ByteOrder + switch string(b[:2]) { + case "II": + order = binary.LittleEndian + case "MM": + order = binary.BigEndian + default: + return 1 + } + if order.Uint16(b[2:4]) != 42 { + return 1 + } + offset := uint64(order.Uint32(b[4:8])) + if offset+2 > uint64(len(b)) { + return 1 + } + count := int(order.Uint16(b[offset : offset+2])) + for i := 0; i < count; i++ { + pos := offset + 2 + uint64(i)*12 + if pos+12 > uint64(len(b)) { + return 1 + } + entry := b[pos : pos+12] + if order.Uint16(entry[:2]) == 0x112 && order.Uint16(entry[2:4]) == 3 && order.Uint32(entry[4:8]) == 1 { + v := int(order.Uint16(entry[8:10])) + if v >= 1 && v <= 8 { + return v + } + return 1 + } + } + return 1 +} +func orientPNG(img image.Image, orientation int) image.Image { + switch orientation { + case 2: + return imaging.FlipH(img) + case 3: + return imaging.Rotate180(img) + case 4: + return imaging.FlipV(img) + case 5: + return imaging.Transpose(img) + case 6: + return imaging.Rotate270(img) + case 7: + return imaging.Transverse(img) + case 8: + return imaging.Rotate90(img) + } + return img +} diff --git a/internal/messenger/rehash_test.go b/internal/messenger/rehash_test.go new file mode 100644 index 0000000..7cf784a --- /dev/null +++ b/internal/messenger/rehash_test.go @@ -0,0 +1,62 @@ +package messenger + +import ( + "context" + "encoding/base64" + "golang.org/x/crypto/argon2" + "mtusi/messenger/internal/database" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" +) + +func TestLegacyArgon2RehashOnHTTPLogin(t *testing.T) { + raw, e := os.ReadFile(os.Getenv("DATABASE_TEST_URL_FILE")) + if e != nil { + t.Skip("real PostgreSQL required") + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + db, e := database.Open(ctx, strings.TrimSpace(string(raw))) + if e != nil { + t.Fatal(e) + } + defer db.Close() + salt := []byte("synthetic-salt16") + password := "Synthetic-old-password-123" + hash := argon2.IDKey([]byte(password), salt, 2, 19456, 1, 32) + legacy := "$argon2id$v=19$m=19456,t=2,p=1$" + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash) + if !verifyPassword(password, legacy) || !needsRehash(legacy) { + t.Fatal("legacy verification or upgrade missing") + } + username := "rehash_" + strings.ReplaceAll(uuid(), "-", "")[:16] + id := uuid() + _, e = db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,'Synthetic rehash',$3)", id, username, legacy) + if e != nil { + t.Fatal(e) + } + server := httptest.NewServer(New(db, nil, make([]byte, 32), 3600, nil)) + defer server.Close() + req, _ := http.NewRequest("POST", server.URL+"/api/v1/auth/sessions", nil) + req.SetBasicAuth(username, password) + res, e := server.Client().Do(req) + if e != nil { + t.Fatal(e) + } + res.Body.Close() + if res.StatusCode != 201 { + t.Fatalf("login status %d", res.StatusCode) + } + var updated string + if db.QueryRow(ctx, "SELECT password_hash FROM users WHERE id=$1", id).Scan(&updated) != nil || needsRehash(updated) || !verifyPassword(password, updated) { + t.Fatal("successful login did not safely upgrade stored hash") + } + for _, bad := range []string{"$argon2id$v=19$m=4294967295,t=999,p=2$AA$AA", "$argon2id$v=19$m=0,t=0,p=0$AA$AA"} { + if verifyPassword(password, bad) { + t.Fatal("unbounded PHC accepted") + } + } +} diff --git a/internal/messenger/server.go b/internal/messenger/server.go new file mode 100644 index 0000000..3adabd5 --- /dev/null +++ b/internal/messenger/server.go @@ -0,0 +1,845 @@ +// Package messenger implements the lab6 contract. PostgreSQL is authoritative. +package messenger + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/redis/go-redis/v9" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/trace" + "io" + "log/slog" + "mime" + "mtusi/messenger/internal/telemetry" + "net/http" + "net/url" + "os" + "regexp" + "strconv" + "strings" + "sync/atomic" + "time" + "unicode/utf8" +) + +type User struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt string `json:"created_at"` +} +type Chat struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt string `json:"created_at"` +} +type Message struct { + AttachmentIDs []string `json:"attachment_ids"` + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt string `json:"created_at"` +} +type Page[T any] struct { + Items []T `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func uuid() string { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + panic(err) + } + b[6] = (b[6] & 15) | 64 + b[8] = (b[8] & 63) | 128 + return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) +} + +var uuidRE = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) +var usernameRE = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +func validText(v string, max int) bool { + return utf8.ValidString(v) && strings.TrimSpace(v) != "" && utf8.RuneCountInString(v) <= max +} +func reply(w http.ResponseWriter, status int, v any) { + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} +func fail(w http.ResponseWriter, status int, code, msg string) { + reply(w, status, map[string]any{"error": map[string]string{"code": code, "message": msg, "request_id": w.Header().Get("X-Request-Id")}}) +} +func bad(w http.ResponseWriter) { fail(w, 400, "invalid_request", "Invalid request") } +func missing(w http.ResponseWriter) { fail(w, 404, "not_found", "Object not found") } + +// Decode exact object keys (encoding/json structs alone accept case variants). +// Reject null, duplicate keys, trailing documents and invalid UTF-8 as well. +func decode(w http.ResponseWriter, r *http.Request, dst any, fields ...string) bool { + media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || media != "application/json" { + fail(w, 415, "unsupported_media_type", "Expected application/json") + return false + } + b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) + if err != nil { + if _, ok := err.(*http.MaxBytesError); ok { + fail(w, 413, "payload_too_large", "Body exceeds 1 MiB") + } else { + bad(w) + } + return false + } + if !utf8.Valid(b) { + bad(w) + return false + } + d := json.NewDecoder(bytes.NewReader(b)) + token, err := d.Token() + if err != nil || token != json.Delim('{') { + bad(w) + return false + } + allowed := map[string]bool{} + for _, f := range fields { + allowed[strings.TrimSuffix(f, "?")] = true + } + seen := map[string]bool{} + for d.More() { + t, e := d.Token() + k, ok := t.(string) + if e != nil || !ok || !allowed[k] || seen[k] { + bad(w) + return false + } + seen[k] = true + var raw json.RawMessage + if d.Decode(&raw) != nil || bytes.Equal(raw, []byte("null")) { + bad(w) + return false + } + } + if _, err = d.Token(); err != nil { + bad(w) + return false + } + if _, err = d.Token(); err != io.EOF { + bad(w) + return false + } + for _, f := range fields { + if !strings.HasSuffix(f, "?") && !seen[f] { + bad(w) + return false + } + } + if json.Unmarshal(b, dst) != nil { + bad(w) + return false + } + return true +} + +type cursor struct { + Scope string `json:"scope"` + Time string `json:"time"` + ID string `json:"id"` +} + +func (s *Server) encodeCursor(c cursor) *string { + b, _ := json.Marshal(c) + mac := hmac.New(sha256.New, s.secret) + mac.Write(b) + v := base64.RawURLEncoding.EncodeToString(b) + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) + return &v +} +func (s *Server) pagination(w http.ResponseWriter, r *http.Request, scope string) (int, cursor, bool) { + var c cursor + limit := 50 + // ParseQuery explicitly reports malformed escaping, unlike URL.Query. + values, e := url.ParseQuery(r.URL.RawQuery) + if e != nil { + bad(w) + return 0, c, false + } + if v, ok := values["limit"]; ok { + if len(v) != 1 || v[0] == "" || strings.Trim(v[0], "0123456789") != "" { + bad(w) + return 0, c, false + } + limit, e = strconv.Atoi(v[0]) + if e != nil || limit < 1 || limit > 100 { + bad(w) + return 0, c, false + } + } + if v, ok := values["cursor"]; ok { + if len(v) != 1 || len(v[0]) > 2048 { + bad(w) + return 0, c, false + } + parts := strings.Split(v[0], ".") + if len(parts) != 2 { + bad(w) + return 0, c, false + } + b, e1 := base64.RawURLEncoding.DecodeString(parts[0]) + sig, e2 := base64.RawURLEncoding.DecodeString(parts[1]) + mac := hmac.New(sha256.New, s.secret) + mac.Write(b) + if e1 != nil || e2 != nil || !hmac.Equal(sig, mac.Sum(nil)) || json.Unmarshal(b, &c) != nil || c.Scope != scope || !uuidRE.MatchString(c.ID) { + bad(w) + return 0, c, false + } + } + if c.ID != "" { + if _, err := time.Parse(time.RFC3339Nano, c.Time); err != nil { + bad(w) + return 0, c, false + } + } + return limit, c, true +} + +type Server struct { + db *pgxpool.Pool + cache *redis.Client + secret []byte + ttl int + log *slog.Logger + stopping atomic.Bool + kdf chan struct{} + objects *ObjectStore + uploads chan struct{} + instance string + dummyHash string +} + +func New(db *pgxpool.Pool, cache *redis.Client, secret []byte, ttl int, logger *slog.Logger) *Server { + hostname := uuid() + _ = os.WriteFile("/run/runtime/instance_alias", []byte(hostname), 0600) + return &Server{instance: hostname, db: db, cache: cache, secret: secret, ttl: ttl, log: logger, kdf: make(chan struct{}, 2), dummyHash: hashPassword("dummy-not-a-real-password")} +} +func (s *Server) Stop() { s.stopping.Store(true) } +func (s *Server) acquireKDF(ctx context.Context, w http.ResponseWriter) bool { + select { + case s.kdf <- struct{}{}: + return true + default: + w.Header().Set("Retry-After", "1") + fail(w, 429, "rate_limited", "Authentication capacity exceeded") + return false + } +} +func unavailable(w http.ResponseWriter) { + fail(w, 503, "unavailable", "Dependency temporarily unavailable") +} +func unauthorized(w http.ResponseWriter, scheme string) { + challenge := scheme + ` realm="messenger"` + if scheme == "Basic" { + challenge += `, charset="UTF-8"` + } + w.Header().Set("WWW-Authenticate", challenge) + fail(w, 401, "unauthorized", "Invalid or missing credentials") +} +func stamp(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000000Z") } + +const userColumns = "id::text, username, display_name, created_at" + +type scanner interface{ Scan(...any) error } + +func scanUser(row scanner) (User, error) { + var u User + var t time.Time + err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &t) + u.CreatedAt = stamp(t) + return u, err +} +func scanMessage(row scanner) (Message, error) { + var m Message + var t time.Time + err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &t) + m.CreatedAt = stamp(t) + m.AttachmentIDs = []string{} + return m, err +} + +func (s *Server) profile(ctx context.Context, uid string) (User, error) { + // Valkey caches ONLY immutable User JSON. Session validity is always read + // from PostgreSQL first; cache loss never permits anonymous access. + key := "profile:v1:" + uid + if s.cache != nil { + c, cancel := context.WithTimeout(ctx, 80*time.Millisecond) + raw, err := s.cache.Get(c, key).Bytes() + cancel() + var u User + if err == nil && json.Unmarshal(raw, &u) == nil && u.ID == uid { + return u, nil + } + } + u, err := scanUser(s.db.QueryRow(ctx, "SELECT "+userColumns+" FROM users WHERE id=$1", uid)) + if err != nil { + return u, err + } + if s.cache != nil { + raw, _ := json.Marshal(u) + c, cancel := context.WithTimeout(ctx, 80*time.Millisecond) + _ = s.cache.Set(c, key, raw, 300*time.Second).Err() + cancel() + } + return u, nil +} +func (s *Server) authenticate(w http.ResponseWriter, r *http.Request) (User, []byte, bool) { + parts := strings.Fields(r.Header.Get("Authorization")) + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { + unauthorized(w, "Bearer") + return User{}, nil, false + } + raw, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil || len(raw) != 32 { + unauthorized(w, "Bearer") + return User{}, nil, false + } + digest := sha256.Sum256([]byte(parts[1])) + var uid string + err = s.db.QueryRow(r.Context(), "SELECT user_id::text FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp()", digest[:]).Scan(&uid) + if errors.Is(err, pgx.ErrNoRows) { + unauthorized(w, "Bearer") + return User{}, nil, false + } + if err != nil { + unavailable(w) + return User{}, nil, false + } + u, err := s.profile(r.Context(), uid) + if err != nil { + unavailable(w) + return User{}, nil, false + } + return u, digest[:], true +} + +type recorder struct { + http.ResponseWriter + status int +} + +func (w *recorder) WriteHeader(status int) { w.status = status; w.ResponseWriter.WriteHeader(status) } +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + start := time.Now() + ctxSpan, span := telemetry.Start(telemetry.Incoming(r), "http.request", trace.SpanKindServer) + r = r.WithContext(ctxSpan) + defer span.End() + out := &recorder{w, 200} + w = out + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("X-Request-Id", uuid()) + w.Header().Set("X-Instance-Id", s.instance) + budget := 3 * time.Second + if strings.Contains(r.URL.Path, "attachments") { + budget = 30 * time.Second + } + ctx, cancel := context.WithTimeout(r.Context(), budget) + defer cancel() + r = r.WithContext(ctx) + if span.SpanContext().IsValid() { + w.Header().Set("X-Trace-Id", telemetry.TraceID(ctx)) + } + route := routeTemplate(r.URL.Path) + defer func() { + if recover() != nil { + fail(w, 500, "internal_error", "Internal server error") + } + span.SetName(r.Method + " " + route) + span.SetAttributes(attribute.String("http.request.method", r.Method), attribute.String("http.route", route), attribute.Int("http.response.status_code", out.status)) + if out.status >= 500 { + span.SetStatus(codes.Error, "HTTP 5xx") + } + telemetry.HTTP(ctx, r.Method, route, out.status, time.Since(start).Seconds()) + if s.log != nil { + s.log.InfoContext(ctx, "request", "method", r.Method, "route", route, "status", out.status, "duration_us", time.Since(start).Microseconds(), "request_id", w.Header().Get("X-Request-Id")) + } + }() + if r.Method == "GET" && (r.URL.Path == "/health/live" || r.URL.Path == "/health/ready") { + if r.URL.Path == "/health/ready" && (s.stopping.Load() || s.db.Ping(ctx) != nil || (s.objects != nil && !s.objects.Ready(ctx))) { + unavailable(w) + } else { + reply(w, 200, map[string]string{"status": "ok"}) + } + return + } + if s.stopping.Load() { + unavailable(w) + return + } + if r.Method == "POST" && r.URL.Path == "/api/v1/users" { + s.createUser(w, r) + return + } + if r.Method == "POST" && r.URL.Path == "/api/v1/auth/sessions" { + s.login(w, r) + return + } + user, digest, ok := s.authenticate(w, r) + if !ok { + return + } + if r.Method == "DELETE" && r.URL.Path == "/api/v1/auth/sessions/current" { + tag, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", digest) + if err != nil { + unavailable(w) + } else if tag.RowsAffected() == 0 { + unauthorized(w, "Bearer") + } else { + w.WriteHeader(204) + } + return + } + if r.Method == "GET" && r.URL.Path == "/api/v1/users/me" { + reply(w, 200, user) + return + } + if r.URL.Path == "/api/v1/chats" { + switch r.Method { + case "POST": + s.createChat(w, r, user.ID) + case "GET": + s.listChats(w, r, user.ID) + default: + missing(w) + } + return + } + parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/") + if len(parts) >= 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && s.objects != nil { + s.serveAttachment(w, r, user.ID, parts) + return + } + if len(parts) < 4 || len(parts) > 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "chats" { + missing(w) + return + } + cid := strings.ToLower(parts[3]) + if !uuidRE.MatchString(cid) { + bad(w) + return + } + chat, err := s.getChat(ctx, cid, user.ID) + if errors.Is(err, pgx.ErrNoRows) { + missing(w) + return + } + if err != nil { + unavailable(w) + return + } + if len(parts) == 4 && r.Method == "GET" { + reply(w, 200, chat) + return + } + if len(parts) == 5 && parts[4] == "attachments" && r.Method == "POST" && s.objects != nil { + s.uploadAttachment(w, r, user.ID, cid) + return + } + if len(parts) == 5 && parts[4] == "messages" { + switch r.Method { + case "POST": + s.createMessage(w, r, user.ID, cid) + case "GET": + s.listMessages(w, r, cid) + default: + missing(w) + } + return + } + missing(w) +} +func (s *Server) createUser(w http.ResponseWriter, r *http.Request) { + var input struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` + } + if !decode(w, r, &input, "username", "display_name", "password") { + return + } + if !usernameRE.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validText(input.Password, 128) || utf8.RuneCountInString(input.Password) < 12 { + bad(w) + return + } + if !s.acquireKDF(r.Context(), w) { + return + } + if !s.admitAuth(w, r, input.Username) { + return + } + hash := hashPassword(input.Password) + <-s.kdf + u, err := scanUser(s.db.QueryRow(r.Context(), "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4) RETURNING "+userColumns, uuid(), input.Username, input.DisplayName, hash)) + var pgerr *pgconn.PgError + if errors.As(err, &pgerr) && pgerr.Code == "23505" { + fail(w, 409, "conflict", "Username already exists") + return + } + if err != nil { + unavailable(w) + return + } + reply(w, 201, u) +} +func (s *Server) login(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1)) + if err != nil || len(body) != 0 { + bad(w) + return + } + username, password, ok := r.BasicAuth() + if !ok || !usernameRE.MatchString(username) || !validText(password, 128) || utf8.RuneCountInString(password) < 12 { + unauthorized(w, "Basic") + return + } + if !s.admitAuth(w, r, username) { + return + } + var u User + var hash string + var t time.Time + err = s.db.QueryRow(r.Context(), "SELECT "+userColumns+", password_hash FROM users WHERE username=$1", username).Scan(&u.ID, &u.Username, &u.DisplayName, &t, &hash) + absent := errors.Is(err, pgx.ErrNoRows) + if err != nil && !absent { + unavailable(w) + return + } + if absent { + hash = s.dummyHash + } + if !s.acquireKDF(r.Context(), w) { + return + } + valid := verifyPassword(password, hash) + if valid && !absent && needsRehash(hash) { + replacement := hashPassword(password) + _, err = s.db.Exec(r.Context(), "UPDATE users SET password_hash=$1 WHERE id=$2 AND password_hash=$3", replacement, u.ID, hash) + if err != nil { + <-s.kdf + unavailable(w) + return + } + } + <-s.kdf + if !valid || absent { + unauthorized(w, "Basic") + return + } + raw := make([]byte, 32) + if _, err = rand.Read(raw); err != nil { + panic(err) + } + token := base64.RawURLEncoding.EncodeToString(raw) + digest := sha256.Sum256([]byte(token)) + var expires time.Time + err = s.db.QueryRow(r.Context(), "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,clock_timestamp()+make_interval(secs=>$3)) RETURNING expires_at", digest[:], u.ID, s.ttl).Scan(&expires) + if err != nil { + unavailable(w) + return + } + u.CreatedAt = stamp(t) + reply(w, 201, map[string]any{"token": token, "token_type": "Bearer", "expires_at": stamp(expires), "user": u}) +} +func (s *Server) createChat(w http.ResponseWriter, r *http.Request, uid string) { + var input struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + } + if !decode(w, r, &input, "title", "member_ids") { + return + } + if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 { + bad(w) + return + } + seen := map[string]bool{} + for i, id := range input.MemberIDs { + id = strings.ToLower(id) + if !uuidRE.MatchString(id) || seen[id] { + bad(w) + return + } + seen[id] = true + input.MemberIDs[i] = id + } + if !seen[uid] { + bad(w) + return + } + tx, err := s.db.Begin(r.Context()) + if err != nil { + unavailable(w) + return + } + defer tx.Rollback(context.Background()) + chat := Chat{ID: uuid(), Title: input.Title, MemberIDs: input.MemberIDs} + var t time.Time + err = tx.QueryRow(r.Context(), "INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at", chat.ID, chat.Title).Scan(&t) + if err != nil { + unavailable(w) + return + } + for _, id := range input.MemberIDs { + _, err = tx.Exec(r.Context(), "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", chat.ID, id) + var pgerr *pgconn.PgError + if errors.As(err, &pgerr) && pgerr.Code == "23503" { + bad(w) + return + } + if err != nil { + unavailable(w) + return + } + } + if tx.Commit(r.Context()) != nil { + unavailable(w) + return + } + chat.CreatedAt = stamp(t) + reply(w, 201, chat) +} + +const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.user_id)` + +func scanChat(row scanner) (Chat, error) { + var c Chat + var t time.Time + err := row.Scan(&c.ID, &c.Title, &t, &c.MemberIDs) + c.CreatedAt = stamp(t) + return c, err +} +func (s *Server) getChat(ctx context.Context, cid, uid string) (Chat, error) { + return scanChat(s.db.QueryRow(ctx, "SELECT "+chatColumns+" FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$2 WHERE c.id=$1", cid, uid)) +} + +var idempotencyRE = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +func (s *Server) createMessage(w http.ResponseWriter, r *http.Request, uid, cid string) { + text, attachments, ok := parseMessage(w, r) + if !ok { + return + } + input := struct { + Text string `json:"text"` + Attachments []string `json:"attachment_ids"` + }{text, attachments} + keys := r.Header.Values("Idempotency-Key") + if len(keys) != 1 || !idempotencyRE.MatchString(keys[0]) { + bad(w) + return + } + body, _ := json.Marshal(input) + digest := sha256.Sum256(body) + ctx := r.Context() + tx, err := s.db.Begin(ctx) + if err != nil { + unavailable(w) + return + } + defer tx.Rollback(context.Background()) + // Serialize only the same scope/key, across processes. Hash collisions only + // serialize unrelated requests; the full unique key still decides identity. + _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", uid+":"+cid+":"+keys[0]) + if err != nil { + unavailable(w) + return + } + var previous, saved []byte + err = tx.QueryRow(ctx, "SELECT body_hash,response FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()", uid, cid, keys[0]).Scan(&previous, &saved) + if err == nil { + if !bytes.Equal(previous, digest[:]) { + fail(w, 409, "conflict", "Key already used with another message") + return + } + if tx.Commit(ctx) != nil { + unavailable(w) + return + } + w.WriteHeader(201) + _, _ = w.Write(saved) + return + } + if !errors.Is(err, pgx.ErrNoRows) { + unavailable(w) + return + } + // A row lock prevents cleanup of an attachment while a message links it. + for _, id := range attachments { + var found, status string + err = tx.QueryRow(ctx, "SELECT id::text,status FROM attachments WHERE id=$1 AND chat_id=$2 FOR SHARE", id, cid).Scan(&found, &status) + if errors.Is(err, pgx.ErrNoRows) { + missing(w) + return + } + if err != nil { + unavailable(w) + return + } + if status == "failed" { + fail(w, 409, "conflict", "Attachment processing failed") + return + } + } + var t time.Time + err = tx.QueryRow(ctx, "UPDATE chats SET last_message_at=GREATEST(clock_timestamp(),last_message_at+interval '1 microsecond') WHERE id=$1 RETURNING last_message_at", cid).Scan(&t) + if err != nil { + unavailable(w) + return + } + m, err := scanMessage(tx.QueryRow(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5) RETURNING id::text,chat_id::text,sender_id::text,text,created_at", uuid(), cid, uid, input.Text, t)) + if err != nil { + unavailable(w) + return + } + m.AttachmentIDs = attachments + for i, id := range attachments { + if _, err = tx.Exec(ctx, "INSERT INTO message_attachments(message_id,attachment_id,position) VALUES($1,$2,$3)", m.ID, id, i); err != nil { + unavailable(w) + return + } + } + response, _ := json.Marshal(m) + _, err = tx.Exec(ctx, `INSERT INTO message_requests(user_id,chat_id,key,body_hash,response,expires_at) VALUES($1,$2,$3,$4,$5,clock_timestamp()+interval '24 hours') ON CONFLICT(user_id,chat_id,key) DO UPDATE SET body_hash=EXCLUDED.body_hash,response=EXCLUDED.response,expires_at=EXCLUDED.expires_at`, uid, cid, keys[0], digest[:], response) + if err != nil || tx.Commit(ctx) != nil { + unavailable(w) + return + } + reply(w, 201, m) +} +func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, cid string) { + scope := "messages:" + cid + limit, c, ok := s.pagination(w, r, scope) + if !ok { + return + } + query := `SELECT id::text,chat_id::text,sender_id::text,text,created_at,ARRAY(SELECT attachment_id::text FROM message_attachments ma WHERE ma.message_id=messages.id ORDER BY position) FROM messages WHERE chat_id=$1` + args := []any{cid} + if c.ID != "" { + query += ` AND (created_at,id)>($2::timestamptz,$3::uuid)` + args = append(args, c.Time, c.ID) + } + query += fmt.Sprintf(" ORDER BY messages.created_at,messages.id LIMIT $%d", len(args)+1) + args = append(args, limit+1) + rows, err := s.db.Query(r.Context(), query, args...) + if err != nil { + unavailable(w) + return + } + defer rows.Close() + items := []Message{} + for rows.Next() { + var m Message + var created time.Time + err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &created, &m.AttachmentIDs) + m.CreatedAt = stamp(created) + if err != nil { + unavailable(w) + return + } + items = append(items, m) + } + if rows.Err() != nil { + unavailable(w) + return + } + var next *string + if len(items) > limit { + items = items[:limit] + last := items[limit-1] + next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID}) + } + reply(w, 200, Page[Message]{items, next}) +} +func (s *Server) listChats(w http.ResponseWriter, r *http.Request, uid string) { + scope := "chats:" + uid + limit, c, ok := s.pagination(w, r, scope) + if !ok { + return + } + query := "SELECT " + chatColumns + " FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$1" + args := []any{uid} + if c.ID != "" { + query += " WHERE (c.created_at,c.id)>($2::timestamptz,$3::uuid)" + args = append(args, c.Time, c.ID) + } + query += fmt.Sprintf(" ORDER BY c.created_at,c.id LIMIT $%d", len(args)+1) + args = append(args, limit+1) + rows, err := s.db.Query(r.Context(), query, args...) + if err != nil { + unavailable(w) + return + } + defer rows.Close() + items := []Chat{} + for rows.Next() { + chat, err := scanChat(rows) + if err != nil { + unavailable(w) + return + } + items = append(items, chat) + } + if rows.Err() != nil { + unavailable(w) + return + } + var next *string + if len(items) > limit { + items = items[:limit] + last := items[limit-1] + next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID}) + } + reply(w, 200, Page[Chat]{items, next}) +} + +// Classify before authentication/SQL so failures retain the endpoint template. +func routeTemplate(path string) string { + switch path { + case "/health/live", "/health/ready": + return path + } + if !strings.HasPrefix(path, "/api/v1/") { + return "unknown" + } + tail := strings.TrimPrefix(path, "/api/v1") + switch tail { + case "/users", "/users/me", "/auth/sessions", "/auth/sessions/current", "/chats": + return tail + } + p := strings.Split(strings.TrimPrefix(tail, "/"), "/") + if len(p) == 2 && p[0] == "chats" { + return "/chats/{id}" + } + if len(p) == 3 && p[0] == "chats" { + switch p[2] { + case "messages": + return "/chats/{id}/messages" + case "attachments": + return "/chats/{id}/attachments" + } + } + if len(p) == 2 && p[0] == "attachments" { + return "/attachments/{id}" + } + if len(p) == 3 && p[0] == "attachments" && p[2] == "content" { + return "/attachments/{id}/content" + } + return "unknown" +} diff --git a/internal/messenger/transform.go b/internal/messenger/transform.go new file mode 100644 index 0000000..3d9624d --- /dev/null +++ b/internal/messenger/transform.go @@ -0,0 +1,104 @@ +package messenger + +import ( + "encoding/json" + "fmt" + "github.com/disintegration/imaging" + "image" + "image/color" + "image/draw" + "image/jpeg" + "image/png" + "math" + "os" + "os/exec" + "path/filepath" +) + +type Variant struct { + Name string `json:"name"` + ContentType string `json:"content_type"` + Size int64 `json:"size_bytes"` + Width int `json:"width"` + Height int `json:"height"` + SHA256 string `json:"sha256"` +} + +func fitDimensions(w, h, max int) (int, int) { + scale := math.Min(1, math.Min(float64(max)/float64(w), float64(max)/float64(h))) + return int(math.Max(1, math.Floor(float64(w)*scale))), int(math.Max(1, math.Floor(float64(h)*scale))) +} + +// Runs in a disposable child process, killed by the parent's 20s deadline. +// The only paths are server-generated temp paths. No client arguments/shell. +func Transform(input, dir string, versions ...int) error { + version := 1 + if len(versions) > 0 { + version = versions[0] + } + if version < 1 || version > 2 { + return fmt.Errorf("unknown pipeline version") + } + quality, webpQuality := 85, "80" + if version == 2 { + quality, webpQuality = 90, "82" + } + f, e := os.Open(input) + if e != nil { + return e + } + c, format, e := image.DecodeConfig(f) + f.Close() + if e != nil || c.Width < 1 || c.Height < 1 || int64(c.Width)*int64(c.Height) > maxPixels { + return ErrInvalidImage + } + img, e := imaging.Open(input, imaging.AutoOrientation(true)) + if e != nil { + return ErrInvalidImage + } + var oriented image.Image = img + if format == "png" { + oriented = orientPNG(img, pngOrientation(input)) + } + bounds := oriented.Bounds() + white := image.NewNRGBA(bounds) + draw.Draw(white, bounds, &image.Uniform{C: color.White}, image.Point{}, draw.Src) + draw.Draw(white, bounds, oriented, bounds.Min, draw.Over) + w, h := fitDimensions(bounds.Dx(), bounds.Dy(), 256) + thumbnail := imaging.Resize(white, w, h, imaging.Lanczos) + crop := imaging.Fill(white, 128, 128, imaging.Center, imaging.Lanczos) + for name, result := range map[string]image.Image{"thumbnail": thumbnail, "crop": crop} { + f, e := os.Create(filepath.Join(dir, name)) + if e != nil { + return e + } + e = jpeg.Encode(f, result, &jpeg.Options{Quality: quality}) + ce := f.Close() + if e != nil { + return e + } + if ce != nil { + return ce + } + } + ow, oh := fitDimensions(bounds.Dx(), bounds.Dy(), 1280) + optimized := imaging.Resize(white, ow, oh, imaging.Lanczos) + p := filepath.Join(dir, "optimized.png") + f, e = os.Create(p) + if e != nil { + return e + } + e = png.Encode(f, optimized) + f.Close() + if e != nil { + return e + } + // Decoding/re-encoding removes EXIF and other source metadata. WebP quality 80. + cmd := exec.Command("cwebp", "-quiet", "-q", webpQuality, "-m", "4", "-metadata", "none", p, "-o", filepath.Join(dir, "optimized")) + if e = cmd.Run(); e != nil { + return fmt.Errorf("webp_encode") + } + result := []Variant{{Name: "thumbnail", ContentType: "image/jpeg", Width: w, Height: h}, {Name: "crop", ContentType: "image/jpeg", Width: 128, Height: 128}, {Name: "optimized", ContentType: "image/webp", Width: ow, Height: oh}} + b, _ := json.Marshal(result) + return os.WriteFile(filepath.Join(dir, "variants.json"), b, 0600) +} diff --git a/internal/messenger/transform_failure_test.go b/internal/messenger/transform_failure_test.go new file mode 100644 index 0000000..a22d834 --- /dev/null +++ b/internal/messenger/transform_failure_test.go @@ -0,0 +1,23 @@ +package messenger + +import ( + "context" + "errors" + "os/exec" + "testing" +) + +func TestTransformFailureClassification(t *testing.T) { + for _, c := range []struct { + command string + invalid bool + }{{"exit 65", true}, {"exit 2", false}, {"kill -KILL $$", false}} { + e := exec.Command("sh", "-c", c.command).Run() + if errors.Is(classifyTransformFailure(nil, e), ErrInvalidImage) != c.invalid { + t.Fatalf("misclassified encoder termination %q", c.command) + } + } + if !errors.Is(classifyTransformFailure(context.DeadlineExceeded, nil), context.DeadlineExceeded) { + t.Fatal("deadline lost") + } +} diff --git a/internal/messenger/transform_test.go b/internal/messenger/transform_test.go new file mode 100644 index 0000000..0d7799f --- /dev/null +++ b/internal/messenger/transform_test.go @@ -0,0 +1,118 @@ +package messenger + +import ( + "bytes" + "encoding/binary" + "hash/crc32" + "image" + "image/color" + "image/jpeg" + "image/png" + "os" + "os/exec" + "path/filepath" + "testing" +) + +func TestFitFloorNoUpscale(t *testing.T) { + for _, v := range [][5]int{{320, 200, 256, 256, 160}, {3, 2, 256, 3, 2}, {301, 200, 256, 256, 170}, {1, 40000, 256, 1, 256}} { + w, h := fitDimensions(v[0], v[1], v[2]) + if w != v[3] || h != v[4] { + t.Fatalf("fit %v got %dx%d", v, w, h) + } + } +} +func TestTransformAlphaAndEXIF(t *testing.T) { + if _, e := exec.LookPath("cwebp"); e != nil { + t.Skip("cwebp provided by Docker test target") + } + dir := t.TempDir() + input := filepath.Join(dir, "input.png") + f, _ := os.Create(input) + png.Encode(f, image.NewNRGBA(image.Rect(0, 0, 320, 200))) + f.Close() + if e := Transform(input, dir); e != nil { + t.Fatal(e) + } + b, _ := os.ReadFile(filepath.Join(dir, "thumbnail")) + img, e := jpeg.Decode(bytes.NewReader(b)) + if e != nil { + t.Fatal(e) + } + r, g, bl, _ := img.At(20, 20).RGBA() + if r < 65000 || g < 65000 || bl < 65000 { + t.Fatal("alpha not composited white") + } + if img.Bounds().Dx() != 256 || img.Bounds().Dy() != 160 { + t.Fatal(img.Bounds()) + } + source := image.NewNRGBA(image.Rect(0, 0, 320, 200)) + source.Set(0, 0, color.White) + var jpg bytes.Buffer + jpeg.Encode(&jpg, source, nil) + // APP1 Exif, little endian TIFF, orientation=6 (90 degrees clockwise). + exif := []byte{'E', 'x', 'i', 'f', 0, 0, 'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0} + var oriented bytes.Buffer + oriented.Write(jpg.Bytes()[:2]) + oriented.Write([]byte{255, 225}) + binary.Write(&oriented, binary.BigEndian, uint16(len(exif)+2)) + oriented.Write(exif) + oriented.Write(jpg.Bytes()[2:]) + os.WriteFile(input, oriented.Bytes(), 0600) + if e = Transform(input, dir); e != nil { + t.Fatal(e) + } + b, _ = os.ReadFile(filepath.Join(dir, "thumbnail")) + img, e = jpeg.Decode(bytes.NewReader(b)) + if e != nil { + t.Fatal(e) + } + if img.Bounds().Dx() != 160 || img.Bounds().Dy() != 256 { + t.Fatalf("EXIF ignored: %v", img.Bounds()) + } +} + +func TestPNGEXIFAndMalformedIFD(t *testing.T) { + tiff := []byte{'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0} + if tiffOrientation(tiff) != 6 { + t.Fatal("TIFF orientation") + } + for i := 0; i < len(tiff); i++ { + _ = tiffOrientation(tiff[:i]) + } + bad := append([]byte{}, tiff...) + for i := 4; i < 8; i++ { + bad[i] = 255 + } + if tiffOrientation(bad) != 1 { + t.Fatal("bad IFD offset") + } + var raw bytes.Buffer + png.Encode(&raw, image.NewNRGBA(image.Rect(0, 0, 320, 200))) + var chunk bytes.Buffer + binary.Write(&chunk, binary.BigEndian, uint32(len(tiff))) + chunk.WriteString("eXIf") + chunk.Write(tiff) + binary.Write(&chunk, binary.BigEndian, crc32.ChecksumIEEE(chunk.Bytes()[4:])) + data := append(append(append([]byte{}, raw.Bytes()[:33]...), chunk.Bytes()...), raw.Bytes()[33:]...) + dir := t.TempDir() + input := filepath.Join(dir, "input.png") + os.WriteFile(input, data, 0600) + if pngOrientation(input) != 6 { + t.Fatal("PNG eXIf orientation") + } + if _, e := exec.LookPath("cwebp"); e != nil { + return + } + if e := Transform(input, dir); e != nil { + t.Fatal(e) + } + b, _ := os.ReadFile(filepath.Join(dir, "thumbnail")) + img, e := jpeg.Decode(bytes.NewReader(b)) + if e != nil { + t.Fatal(e) + } + if img.Bounds().Dx() != 160 || img.Bounds().Dy() != 256 { + t.Fatal("PNG orientation not applied", img.Bounds()) + } +} diff --git a/internal/security/gateway.go b/internal/security/gateway.go new file mode 100644 index 0000000..23690ba --- /dev/null +++ b/internal/security/gateway.go @@ -0,0 +1,133 @@ +package security + +import ( + "context" + "crypto/tls" + "encoding/json" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "net/http/httputil" + "net/url" + "os" + "strings" + "time" +) + +type Rule struct { + Identity string `json:"identity"` + Methods []string `json:"methods"` + Prefixes []string `json:"prefixes"` +} +type Listener struct { + Listen string `json:"listen"` + Target string `json:"target"` + Raw bool `json:"raw"` + Identities []string `json:"identities"` + Rules []Rule `json:"rules"` +} + +// The plaintext upstream is always loopback in the SAME network namespace. +// Services have no native listener on the container network or published port. +func Gateway(ctx context.Context, path string) error { + b, e := os.ReadFile(path) + if e != nil { + return e + } + var configs []Listener + if e = json.Unmarshal(b, &configs); e != nil { + return e + } + errors := make(chan error, len(configs)) + for _, cfg := range configs { + cfg := cfg + host, _, e := net.SplitHostPort(cfg.Target) + if e != nil || host != "127.0.0.1" { + return fmt.Errorf("gateway upstream must be loopback") + } + tc, e := ServerTLS(cfg.Identities) + if e != nil { + return e + } + ln, e := tls.Listen("tcp", cfg.Listen, tc) + if e != nil { + return e + } + go func() { <-ctx.Done(); ln.Close() }() + if cfg.Raw { + go func() { + for { + c, e := ln.Accept() + if e != nil { + errors <- e + return + } + go func() { + defer c.Close() + c.SetDeadline(time.Now().Add(30 * time.Second)) + if e := c.(*tls.Conn).Handshake(); e != nil { + return + } + up, e := net.DialTimeout("tcp", cfg.Target, time.Second) + if e != nil { + return + } + defer up.Close() + up.SetDeadline(time.Now().Add(30 * time.Second)) + go io.Copy(up, c) + io.Copy(c, up) + }() + } + }() + continue + } + u, _ := url.Parse("http://" + cfg.Target) + proxy := httputil.NewSingleHostReverseProxy(u) + proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) { http.Error(w, "upstream unavailable", 503) } + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if len(cfg.Rules) > 0 { + allowed := false + for _, rule := range cfg.Rules { + if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 { + continue + } + identity := false + for _, san := range r.TLS.PeerCertificates[0].DNSNames { + if san == rule.Identity+".client.lab" { + identity = true + } + } + method := false + for _, v := range rule.Methods { + if v == r.Method { + method = true + } + } + if identity && method { + for _, p := range rule.Prefixes { + if strings.HasPrefix(r.URL.Path, p) { + allowed = true + } + } + } + } + if !allowed { + http.Error(w, "service action forbidden", 403) + return + } + } + proxy.ServeHTTP(w, r) + }) + srv := &http.Server{Handler: AuthorizeHTTP(tc, handler), ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 35 * time.Second, WriteTimeout: 35 * time.Second, IdleTimeout: 2 * time.Second, MaxHeaderBytes: 16 << 10, + ErrorLog: slog.NewLogLogger(slog.NewTextHandler(io.Discard, nil), slog.LevelError)} + go func() { errors <- srv.Serve(ln) }() + } + select { + case <-ctx.Done(): + return nil + case e := <-errors: + return e + } +} diff --git a/internal/security/probe.go b/internal/security/probe.go new file mode 100644 index 0000000..1e47408 --- /dev/null +++ b/internal/security/probe.go @@ -0,0 +1,185 @@ +package security + +import ( + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "strings" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" + "github.com/redis/go-redis/v9" +) + +// Operator-only verifier. Inputs arrive on stdin; private values never appear +// in argv or output. SQL outputs only allow/deny, never returned row contents. +func Probe() error { + var in struct { + Kind, Role, Cert, URL, Method, Body, Query, Key, CredentialsFile, ServerName, Auth string + NoCert, WrongCA, ReturnBody bool + Command []string + } + if json.NewDecoder(io.LimitReader(os.Stdin, 65536)).Decode(&in) != nil { + return fmt.Errorf("invalid probe input") + } + if in.Cert == "" { + in.Cert = "operator" + } + os.Setenv("TLS_CERT_FILE", "/fixtures/"+in.Cert+"/cert.crt") + os.Setenv("TLS_KEY_FILE", "/fixtures/"+in.Cert+"/key.key") + tc, e := ClientTLS() + if e != nil { + return e + } + if in.NoCert { + tc.GetClientCertificate = nil + } + if in.ServerName != "" { + tc.ServerName = in.ServerName + } + if in.WrongCA { + b, _ := os.ReadFile("/operator/alien-ca/ca.crt") + p := x509.NewCertPool() + p.AppendCertsFromPEM(b) + tc.RootCAs = p + } + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + defer cancel() + result := map[string]any{"ok": false} + var creds map[string]json.RawMessage + path := in.CredentialsFile + if path == "" { + path = "/operator/credentials.json" + } + raw, _ := os.ReadFile(path) + json.Unmarshal(raw, &creds) + var role struct { + DBPassword string `json:"db_password"` + BrokerPassword string `json:"broker_password"` + CachePassword string `json:"cache_password"` + Access string `json:"s3_access_key_id"` + Secret string `json:"s3_secret_access_key"` + } + json.Unmarshal(creds[in.Role], &role) + switch in.Kind { + case "http": + if in.Method == "" { + in.Method = "GET" + } + r, e2 := http.NewRequestWithContext(ctx, in.Method, in.URL, strings.NewReader(in.Body)) + if e2 != nil { + return fmt.Errorf("invalid probe URL") + } + r.Header.Set("Content-Type", "application/json") + if in.Auth == "grafana" { + var password string + json.Unmarshal(creds["grafana_password"], &password) + r.SetBasicAuth("admin", password) + } + tr := &http.Transport{TLSClientConfig: tc, DisableKeepAlives: true} + defer tr.CloseIdleConnections() + client := &http.Client{Transport: tr, Timeout: 6 * time.Second} + resp, err := client.Do(r) + e = err + if e == nil { + defer resp.Body.Close() + b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + result["status"] = resp.StatusCode + result["ok"] = resp.StatusCode >= 200 && resp.StatusCode < 300 + result["tls"] = resp.TLS != nil && resp.TLS.Version >= tls.VersionTLS12 + if in.ReturnBody { + result["body"] = string(b) + } + } + case "postgres": + cfg, err := pgx.ParseConfig("postgres://messenger_" + in.Role + ":" + role.DBPassword + "@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/tls/ca.crt") + if err != nil { + return fmt.Errorf("invalid probe role") + } + cfg.TLSConfig = tc.Clone() + if cfg.TLSConfig.ServerName == "" { + cfg.TLSConfig.ServerName = "postgres" + } + cfg.Fallbacks = nil + var conn *pgx.Conn + conn, e = pgx.ConnectConfig(ctx, cfg) + if e == nil { + defer conn.Close(ctx) + _, e = conn.Exec(ctx, in.Query) + result["ok"] = e == nil + } + case "redis": + pass := role.BrokerPassword + user := in.Role + host := "broker" + if in.URL == "cache" { + pass = role.CachePassword + host = "cache" + } + rc := redis.NewClient(&redis.Options{Addr: host + ":6379", Username: user, Password: pass, TLSConfig: tc, MaxRetries: -1, DialTimeout: time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second}) + defer rc.Close() + args := make([]any, len(in.Command)) + for i, v := range in.Command { + args[i] = v + } + _, e = rc.Do(ctx, args...).Result() + result["ok"] = e == nil + case "s3": + tr := &http.Transport{TLSClientConfig: tc} + defer tr.CloseIdleConnections() + client, err := minio.New("s3:9000", &minio.Options{Secure: true, Creds: credentials.NewStaticV4(role.Access, role.Secret, ""), Region: "us-east-1", Transport: tr, MaxRetries: 1}) + if err != nil { + return fmt.Errorf("invalid probe object client") + } + switch in.Method { + case "PUT": + _, e = client.PutObject(ctx, "messenger-attachments", in.Key, strings.NewReader(in.Body), int64(len(in.Body)), minio.PutObjectOptions{}) + case "DELETE": + e = client.RemoveObject(ctx, "messenger-attachments", in.Key, minio.RemoveObjectOptions{}) + case "LIST_BUCKETS": + _, e = client.ListBuckets(ctx) + default: + _, e = client.StatObject(ctx, "messenger-attachments", in.Key, minio.StatObjectOptions{}) + } + result["ok"] = e == nil + default: + return fmt.Errorf("unknown probe kind") + } + if e != nil { + category := "connection_or_action_denied" + if strings.Contains(e.Error(), "NOPERM") || strings.Contains(e.Error(), "permission denied") || strings.Contains(e.Error(), "Access Denied") { + category = "permission_denied" + } + var authority x509.UnknownAuthorityError + var hostname x509.HostnameError + var pg *pgconn.PgError + switch { + case errors.As(e, &authority): + category = "ca_verification_failed" + case errors.As(e, &hostname): + category = "hostname_verification_failed" + case errors.As(e, &pg): + if pg.Code == "42501" { + category = "permission_denied" + } else if pg.Code == "28P01" { + category = "credential_denied" + } + case strings.Contains(e.Error(), "tls:") || strings.Contains(e.Error(), "certificate"): + category = "tls_handshake_denied" + case strings.Contains(e.Error(), "timeout") || strings.Contains(e.Error(), "deadline exceeded"): + category = "timeout" + } + // Generic category only: upstream errors can contain SQL/user names/keys. + result["error_category"] = category + } + return json.NewEncoder(os.Stdout).Encode(result) +} diff --git a/internal/security/supervisor.go b/internal/security/supervisor.go new file mode 100644 index 0000000..8ef404d --- /dev/null +++ b/internal/security/supervisor.go @@ -0,0 +1,172 @@ +package security + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "os" + "os/exec" + "reflect" + "strings" + "syscall" + "time" +) + +func baoRequest(ctx context.Context, client *http.Client, method, path, token string, body any) (map[string]any, error) { + if !strings.HasPrefix(os.Getenv("BAO_ADDR"), "https://") { + return nil, fmt.Errorf("secret service requires HTTPS") + } + b, _ := json.Marshal(body) + r, e := http.NewRequestWithContext(ctx, method, os.Getenv("BAO_ADDR")+"/v1/"+path, bytes.NewReader(b)) + if e != nil { + return nil, fmt.Errorf("invalid secret endpoint") + } + r.Header.Set("Content-Type", "application/json") + if token != "" { + r.Header.Set("X-Vault-Token", token) + } + resp, e := client.Do(r) + if e != nil { + return nil, fmt.Errorf("secret service unavailable") + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + return nil, fmt.Errorf("secret service denied or sealed") + } + var out map[string]any + if json.NewDecoder(io.LimitReader(resp.Body, 65536)).Decode(&out) != nil { + return nil, fmt.Errorf("invalid secret response") + } + return out, nil +} + +// Short-lived certificate auth replaces a permanent bootstrap token. Values +// live only in this process and a tmpfs snapshot consumed by the child. +func fetch(ctx context.Context) (map[string]string, time.Time, error) { + tc, e := ClientTLS() + if e != nil { + return nil, time.Time{}, e + } + transport := &http.Transport{TLSClientConfig: tc} + defer transport.CloseIdleConnections() + client := &http.Client{Transport: transport, Timeout: 3 * time.Second} + login, e := baoRequest(ctx, client, "POST", "auth/cert/login", "", map[string]string{"name": os.Getenv("SERVICE_ID")}) + if e != nil { + return nil, time.Time{}, e + } + auth, ok := login["auth"].(map[string]any) + if !ok { + return nil, time.Time{}, fmt.Errorf("missing service auth") + } + token, _ := auth["client_token"].(string) + ttl, _ := auth["lease_duration"].(float64) + if ttl <= 0 || ttl > 120 { + return nil, time.Time{}, fmt.Errorf("invalid service TTL") + } + defer baoRequest(context.WithoutCancel(ctx), client, "POST", "auth/token/revoke-self", token, map[string]any{}) + data, e := baoRequest(ctx, client, "GET", "kv/data/"+os.Getenv("SERVICE_ID"), token, nil) + if e != nil { + return nil, time.Time{}, e + } + outer, _ := data["data"].(map[string]any) + raw, _ := outer["data"].(map[string]any) + values := map[string]string{} + for k, v := range raw { + if s, ok := v.(string); ok { + values[k] = s + } + } + if values["database_url"] == "" { + return nil, time.Time{}, fmt.Errorf("incomplete service secrets") + } + return values, time.Now().Add(time.Duration(ttl) * time.Second), nil +} +func stopChild(cmd *exec.Cmd, done <-chan error) { + cmd.Process.Signal(syscall.SIGTERM) + select { + case <-done: + case <-time.After(6 * time.Second): + cmd.Process.Kill() + <-done + } +} + +func Supervise(ctx context.Context, args []string) error { + var values map[string]string + var expiry time.Time + var child *exec.Cmd + var done chan error + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + defer func() { + if child != nil { + stopChild(child, done) + } + }() + for { + fresh, until, e := fetch(ctx) + if e == nil { + expiry = until + if child == nil || !reflect.DeepEqual(values, fresh) { + if child != nil { + stopChild(child, done) + child = nil + } + values = fresh + b, _ := json.Marshal(values) + if e = os.WriteFile("/run/runtime/active.json", b, 0600); e != nil { + return fmt.Errorf("runtime secret storage unavailable") + } + executable, _ := os.Executable() + child = exec.Command(executable, args...) + child.Env = append(os.Environ(), "RUNTIME_SECRET_FILE=/run/runtime/active.json") + child.Stdout = os.Stdout + child.Stderr = os.Stderr + if e = child.Start(); e != nil { + return fmt.Errorf("child unavailable") + } + done = make(chan error, 1) + go func(c *exec.Cmd, ch chan error) { ch <- c.Wait() }(child, done) + slog.Info("service credentials installed", "event", "credentials_installed") + } + } else if child != nil && !time.Now().Before(expiry) { + stopChild(child, done) + child = nil + os.Remove("/run/runtime/active.json") + slog.Warn("service authorization expired", "event", "authorization_expired") + } + if child != nil { + select { + case <-done: + child = nil + default: + } + } + select { + case <-ctx.Done(): + return nil + case <-ticker.C: + } + } +} + +func RuntimeSecret(name string) (string, bool) { + path := os.Getenv("RUNTIME_SECRET_FILE") + if path == "" { + return "", false + } + b, e := os.ReadFile(path) + if e != nil { + return "", true + } + var data map[string]string + if json.Unmarshal(b, &data) != nil { + return "", true + } + key := map[string]string{"DATABASE_URL_FILE": "database_url", "CACHE_URL_FILE": "cache_url", "BROKER_URL_FILE": "broker_url", "CURSOR_KEY_FILE": "cursor_key", "S3_ACCESS_KEY_ID_FILE": "s3_access_key_id", "S3_SECRET_ACCESS_KEY_FILE": "s3_secret_access_key"}[name] + return data[key], true +} diff --git a/internal/security/tls.go b/internal/security/tls.go new file mode 100644 index 0000000..8d661d7 --- /dev/null +++ b/internal/security/tls.go @@ -0,0 +1,98 @@ +// Package security implements the lab's explicit trust boundaries. +package security + +import ( + "crypto/tls" + "crypto/x509" + "encoding/json" + "fmt" + "net/http" + "os" + "strings" + "time" +) + +func roots() (*x509.CertPool, error) { + b, e := os.ReadFile(os.Getenv("TLS_CA_FILE")) + if e != nil { + return nil, fmt.Errorf("TLS CA unavailable") + } + p := x509.NewCertPool() + if !p.AppendCertsFromPEM(b) { + return nil, fmt.Errorf("invalid TLS CA") + } + return p, nil +} + +// Recheck revocation on EVERY HTTP request, including an already-open TLS +// connection. An in-flight request remains bounded by the HTTP deadlines. +func AuthorizeHTTP(c *tls.Config, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if c.VerifyConnection != nil && (r.TLS == nil || c.VerifyConnection(*r.TLS) != nil) { + w.Header().Set("Connection", "close") + http.Error(w, "service identity forbidden", 403) + return + } + next.ServeHTTP(w, r) + }) +} +func pair() (*tls.Certificate, error) { + c, e := tls.LoadX509KeyPair(os.Getenv("TLS_CERT_FILE"), os.Getenv("TLS_KEY_FILE")) + if e != nil { + return nil, fmt.Errorf("TLS identity unavailable") + } + return &c, nil +} +func ClientTLS() (*tls.Config, error) { + p, e := roots() + if e != nil { + return nil, e + } + return &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: p, GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { return pair() }}, nil +} + +// VerifyConnection runs even on resumed handshakes. Current CA-validated chain, +// exact DNS SAN and serial denylist all matter, not the certificate CN alone. +func ServerTLS(identities []string) (*tls.Config, error) { + p, e := roots() + if e != nil { + return nil, e + } + c := &tls.Config{MinVersion: tls.VersionTLS12, ClientCAs: p, GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return pair() }, SessionTicketsDisabled: true} + if len(identities) == 0 { + return c, nil + } + c.ClientAuth = tls.RequireAndVerifyClientCert + c.VerifyConnection = func(s tls.ConnectionState) error { + if len(s.VerifiedChains) == 0 || len(s.PeerCertificates) == 0 { + return fmt.Errorf("unverified peer") + } + leaf := s.PeerCertificates[0] + now := time.Now() + if now.Before(leaf.NotBefore) || !now.Before(leaf.NotAfter) { + return fmt.Errorf("identity expired") + } + b, e := os.ReadFile(os.Getenv("TLS_REVOCATIONS_FILE")) + if e != nil { + return fmt.Errorf("revocation state unavailable") + } + var revoked []string + if json.Unmarshal(b, &revoked) != nil { + return fmt.Errorf("invalid revocation state") + } + for _, serial := range revoked { + if strings.EqualFold(serial, leaf.SerialNumber.Text(16)) { + return fmt.Errorf("identity revoked") + } + } + for _, allowed := range identities { + for _, name := range leaf.DNSNames { + if name == allowed+".client.lab" { + return nil + } + } + } + return fmt.Errorf("identity not allowed") + } + return c, nil +} diff --git a/internal/telemetry/db.go b/internal/telemetry/db.go new file mode 100644 index 0000000..4ee9d16 --- /dev/null +++ b/internal/telemetry/db.go @@ -0,0 +1,40 @@ +package telemetry + +import ( + "context" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "go.opentelemetry.io/otel/trace" + "strings" +) + +type DBTracer struct{} + +func (DBTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context { + fields := strings.Fields(d.SQL) + op := "query" + if len(fields) > 0 { + switch strings.ToUpper(fields[0]) { + case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK": + op = strings.ToUpper(fields[0]) + } + } + ctx, _ = Start(ctx, "db."+op, trace.SpanKindClient) + return ctx +} +func (DBTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryEndData) { + s := trace.SpanFromContext(ctx) + Failure(s, d.Err) + s.End() +} +func (DBTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context { + PendingAcquires.Add(1) + ctx, _ = Start(ctx, "db.pool.acquire", trace.SpanKindInternal) + return ctx +} +func (DBTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, d pgxpool.TraceAcquireEndData) { + PendingAcquires.Add(-1) + s := trace.SpanFromContext(ctx) + Failure(s, d.Err) + s.End() +} diff --git a/internal/telemetry/http.go b/internal/telemetry/http.go new file mode 100644 index 0000000..ee4d06c --- /dev/null +++ b/internal/telemetry/http.go @@ -0,0 +1,24 @@ +package telemetry + +import ( + "context" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/trace" + "net/http" +) + +func Incoming(r *http.Request) context.Context { + return otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header)) +} + +type transport struct{ next http.RoundTripper } + +func Transport(next http.RoundTripper) http.RoundTripper { return &transport{next} } +func (t *transport) RoundTrip(r *http.Request) (*http.Response, error) { + ctx, s := Start(r.Context(), "s3.request", trace.SpanKindClient) + defer s.End() + response, e := t.next.RoundTrip(r.Clone(ctx)) + Failure(s, e) + return response, e +} diff --git a/internal/telemetry/telemetry.go b/internal/telemetry/telemetry.go new file mode 100644 index 0000000..86f8d51 --- /dev/null +++ b/internal/telemetry/telemetry.go @@ -0,0 +1,250 @@ +// Package telemetry owns bounded, best-effort OTLP exporters. It never affects +// business readiness and never exports URLs, SQL text, credentials or payloads. +package telemetry + +import ( + "context" + "fmt" + "github.com/jackc/pgx/v5/pgxpool" + "go.opentelemetry.io/contrib/bridges/otelslog" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp" + "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/propagation" + sdklog "go.opentelemetry.io/otel/sdk/log" + sdkmetric "go.opentelemetry.io/otel/sdk/metric" + "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + semconv "go.opentelemetry.io/otel/semconv/v1.32.0" + "go.opentelemetry.io/otel/trace" + "log/slog" + "mtusi/messenger/internal/security" + "os" + "strconv" + "strings" + "sync/atomic" + "time" +) + +var HTTPCount metric.Int64Counter +var HTTPDuration, JobDuration, ReadyDuration metric.Float64Histogram +var Jobs metric.Int64Counter +var PendingAcquires atomic.Int64 +var Busy atomic.Int64 +var capacity atomic.Int64 +var tracer = otel.Tracer("messenger", trace.WithSchemaURL(semconv.SchemaURL)) + +func Init(ctx context.Context, service string) (*slog.Logger, func(), error) { + instance, _ := os.Hostname() + attrs := []attribute.KeyValue{attribute.String("service.name", service), attribute.String("service.version", "7.1.0"), attribute.String("service.instance.id", instance), attribute.String("deployment.environment.name", "lab")} + res := resource.NewWithAttributes(semconv.SchemaURL, attrs...) + otel.SetTextMapPropagator(propagation.TraceContext{}) + if os.Getenv("OTEL_SDK_DISABLED") == "true" { + return slog.New(&contextHandler{next: slog.NewJSONHandler(os.Stdout, nil), service: service}), func() {}, nil + } + if !strings.HasPrefix(os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT"), "https://") { + return nil, nil, fmt.Errorf("telemetry requires verified HTTPS") + } + tc, e := security.ClientTLS() + if e != nil { + return nil, nil, e + } + te, e := otlptracehttp.New(ctx, otlptracehttp.WithTimeout(time.Second), otlptracehttp.WithTLSClientConfig(tc)) + if e != nil { + return nil, nil, e + } + tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(1))), sdktrace.WithBatcher(te, sdktrace.WithMaxQueueSize(1024), sdktrace.WithMaxExportBatchSize(128), sdktrace.WithBatchTimeout(time.Second), sdktrace.WithExportTimeout(time.Second))) + otel.SetTracerProvider(tp) + tracer = otel.Tracer("messenger", trace.WithSchemaURL(semconv.SchemaURL)) + me, e := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTimeout(time.Second), otlpmetrichttp.WithTLSClientConfig(tc)) + if e != nil { + return nil, nil, e + } + mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res), sdkmetric.WithReader(sdkmetric.NewPeriodicReader(me, sdkmetric.WithInterval(2*time.Second), sdkmetric.WithTimeout(time.Second))), sdkmetric.WithView(sdkmetric.NewView(sdkmetric.Instrument{Kind: sdkmetric.InstrumentKindHistogram}, sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{Boundaries: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 20, 30, 60, 120}}}))) + otel.SetMeterProvider(mp) + le, e := otlploghttp.New(ctx, otlploghttp.WithTimeout(time.Second), otlploghttp.WithTLSClientConfig(tc)) + if e != nil { + return nil, nil, e + } + lp := sdklog.NewLoggerProvider(sdklog.WithResource(res), sdklog.WithProcessor(sdklog.NewBatchProcessor(le, sdklog.WithMaxQueueSize(1024), sdklog.WithExportMaxBatchSize(128), sdklog.WithExportInterval(time.Second), sdklog.WithExportTimeout(time.Second)))) + log := slog.New(&contextHandler{next: &tee{a: slog.NewJSONHandler(os.Stdout, nil), b: otelslog.NewHandler("messenger", otelslog.WithLoggerProvider(lp))}, service: service}) + m := otel.Meter("messenger") + HTTPCount, _ = m.Int64Counter("http.server.requests") + HTTPDuration, _ = m.Float64Histogram("http.server.duration", metric.WithUnit("s")) + Jobs, _ = m.Int64Counter("messenger.jobs") + JobDuration, _ = m.Float64Histogram("messenger.job.duration", metric.WithUnit("s")) + ReadyDuration, _ = m.Float64Histogram("messenger.attachment.ready.duration", metric.WithUnit("s")) + shutdown := func() { + c, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + _ = tp.Shutdown(c) + _ = mp.Shutdown(c) + _ = lp.Shutdown(c) + } + return log, shutdown, nil +} +func Start(ctx context.Context, name string, kind trace.SpanKind) (context.Context, trace.Span) { + return tracer.Start(ctx, name, trace.WithSpanKind(kind)) +} +func Failure(span trace.Span, e error) { + if e != nil { + span.SetStatus(codes.Error, "dependency operation failed") + } +} +func Inject(ctx context.Context) (string, string) { + c := propagation.MapCarrier{} + otel.GetTextMapPropagator().Inject(ctx, c) + return c.Get("traceparent"), c.Get("tracestate") +} +func Extract(ctx context.Context, parent, state string) context.Context { + return otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state}) +} +func TraceID(ctx context.Context) string { return trace.SpanContextFromContext(ctx).TraceID().String() } +func HTTP(ctx context.Context, method, route string, status int, seconds float64) { + switch method { + case "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS": + default: + method = "_OTHER" + } + if HTTPCount == nil { + return + } + attrs := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", fmt.Sprintf("%dxx", status/100))) + HTTPCount.Add(ctx, 1, attrs) + HTTPDuration.Record(ctx, seconds, attrs) +} +func Job(ctx context.Context, outcome string, seconds float64) { + if Jobs == nil { + return + } + attrs := metric.WithAttributes(attribute.String("job_type", "attachment.process.v1"), attribute.String("outcome", outcome)) + Jobs.Add(ctx, 1, attrs) + JobDuration.Record(ctx, seconds, attrs) +} +func Ready(ctx context.Context, seconds float64) { + if ReadyDuration != nil { + ReadyDuration.Record(ctx, seconds) + } +} +func WorkerCapacity(n int) { capacity.Store(int64(n)) } +func Observe(pool *pgxpool.Pool, worker bool) { + m := otel.Meter("messenger") + used, _ := m.Int64ObservableGauge("messenger.db.pool.used") + limit, _ := m.Int64ObservableGauge("messenger.db.pool.limit") + waiting, _ := m.Int64ObservableGauge("messenger.db.pool.waiting") + waits, _ := m.Int64ObservableCounter("messenger.db.pool.waits") + depth, _ := m.Int64ObservableGauge("messenger.queue.depth") + age, _ := m.Float64ObservableGauge("messenger.queue.oldest.age", metric.WithUnit("s")) + busy, _ := m.Int64ObservableGauge("messenger.worker.busy") + cap, _ := m.Int64ObservableGauge("messenger.worker.capacity") + sliTotal, _ := m.Int64ObservableCounter("messenger.attachment.sli.total") + sliBad, _ := m.Int64ObservableCounter("messenger.attachment.sli.bad") + containerRSS, _ := m.Int64ObservableGauge("container.memory.usage", metric.WithUnit("By")) + containerCPU, _ := m.Float64ObservableCounter("container.cpu.time", metric.WithUnit("s")) + rss, _ := m.Int64ObservableGauge("process.memory.usage", metric.WithUnit("By")) + cpu, _ := m.Float64ObservableCounter("process.cpu.time", metric.WithUnit("s")) + _, _ = m.RegisterCallback(func(ctx context.Context, o metric.Observer) error { + stat := pool.Stat() + o.ObserveInt64(used, int64(stat.AcquiredConns())) + o.ObserveInt64(limit, int64(stat.MaxConns())) + o.ObserveInt64(waits, stat.EmptyAcquireCount()) + o.ObserveInt64(waiting, PendingAcquires.Load()) + o.ObserveInt64(busy, Busy.Load()) + o.ObserveInt64(cap, capacity.Load()) + mem, cputime := processUsage() + o.ObserveInt64(rss, mem) + o.ObserveFloat64(cpu, cputime) + if raw, e := os.ReadFile("/sys/fs/cgroup/memory.current"); e == nil { + if bytes, e := strconv.ParseInt(strings.TrimSpace(string(raw)), 10, 64); e == nil { + o.ObserveInt64(containerRSS, bytes) + } + } + if raw, e := os.ReadFile("/sys/fs/cgroup/cpu.stat"); e == nil { + for _, line := range strings.Split(string(raw), "\n") { + fields := strings.Fields(line) + if len(fields) == 2 && fields[0] == "usage_usec" { + if us, e := strconv.ParseFloat(fields[1], 64); e == nil { + o.ObserveFloat64(containerCPU, us/1e6) + } + } + } + } + if worker { + // One bounded query on the worker only avoids duplicating global queue + // gauges per API. A DB failure omits the observation, never invents zero. + query, cancel := context.WithTimeout(ctx, 300*time.Millisecond) + defer cancel() + var n int64 + var oldest float64 + e := pool.QueryRow(query, `SELECT count(*),COALESCE(EXTRACT(EPOCH FROM clock_timestamp()-min(created_at)),0)::float8 FROM pipeline_jobs WHERE finished_at IS NULL`).Scan(&n, &oldest) + if e == nil { + o.ObserveInt64(depth, n) + o.ObserveFloat64(age, oldest) + } + var matured, bad int64 + e = pool.QueryRow(query, `SELECT count(*),count(*) FILTER (WHERE ready_at IS NULL OR ready_at>created_at+interval '5 seconds') FROM pipeline_jobs WHERE created_at<=clock_timestamp()-interval '5 seconds'`).Scan(&matured, &bad) + if e == nil { + o.ObserveInt64(sliTotal, matured) + o.ObserveInt64(sliBad, bad) + } + } + return nil + }, used, limit, waits, waiting, depth, age, busy, cap, rss, cpu, sliTotal, sliBad, containerRSS, containerCPU) +} +func processUsage() (int64, float64) { + raw, e := os.ReadFile("/proc/self/stat") + if e != nil { + return 0, 0 + } + end := strings.LastIndex(string(raw), ")") + if end < 0 { + return 0, 0 + } + fields := strings.Fields(string(raw)[end+1:]) + if len(fields) < 22 { + return 0, 0 + } + u, _ := strconv.ParseFloat(fields[11], 64) + s, _ := strconv.ParseFloat(fields[12], 64) + pages, _ := strconv.ParseInt(fields[21], 10, 64) + return pages * int64(os.Getpagesize()), (u + s) / 100 +} + +type contextHandler struct { + next slog.Handler + service string +} + +func (h *contextHandler) Enabled(ctx context.Context, l slog.Level) bool { + return h.next.Enabled(ctx, l) +} +func (h *contextHandler) Handle(ctx context.Context, r slog.Record) error { + r.AddAttrs(slog.String("service.name", h.service), slog.String("event", r.Message)) + sc := trace.SpanContextFromContext(ctx) + if sc.IsValid() { + r.AddAttrs(slog.String("trace_id", sc.TraceID().String()), slog.String("span_id", sc.SpanID().String())) + } + return h.next.Handle(ctx, r) +} +func (h *contextHandler) WithAttrs(a []slog.Attr) slog.Handler { + return &contextHandler{next: h.next.WithAttrs(a), service: h.service} +} +func (h *contextHandler) WithGroup(g string) slog.Handler { + return &contextHandler{next: h.next.WithGroup(g), service: h.service} +} + +type tee struct{ a, b slog.Handler } + +func (h *tee) Enabled(ctx context.Context, l slog.Level) bool { + return h.a.Enabled(ctx, l) || h.b.Enabled(ctx, l) +} +func (h *tee) Handle(ctx context.Context, r slog.Record) error { + _ = h.a.Handle(ctx, r.Clone()) + return h.b.Handle(ctx, r) +} +func (h *tee) WithAttrs(a []slog.Attr) slog.Handler { return &tee{h.a.WithAttrs(a), h.b.WithAttrs(a)} } +func (h *tee) WithGroup(g string) slog.Handler { return &tee{h.a.WithGroup(g), h.b.WithGroup(g)} } diff --git a/scripts/bao_operator.py b/scripts/bao_operator.py new file mode 100644 index 0000000..b94a182 --- /dev/null +++ b/scripts/bao_operator.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Explicit operator init/unseal/configuration. Never mounted into application.""" +import json,os,ssl,subprocess,sys,time,urllib.error,urllib.request +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1];OP=ROOT/'secrets/operator' +def port(name,default): + if name in os.environ:return os.environ[name] + for line in (ROOT/'.env').read_text().splitlines(): + if line.startswith(name+'='):return line.split('=',1)[1] + return default +BASE='https://localhost:'+port('BAO_PORT','8207') +def request(method,path,data=None,token=None,cert=None,expect=(200,204)): + ctx=ssl.create_default_context(cafile=str(ROOT/'certs/ca.crt')) + if cert:ctx.load_cert_chain(str(ROOT/'certs/private'/cert/'cert.crt'),str(ROOT/'certs/private'/cert/'key.key')) + headers={'Content-Type':'application/json'} + if token:headers['X-Vault-Token']=token + body=json.dumps(data).encode() if data is not None else None + req=urllib.request.Request(BASE+'/v1/'+path,data=body,headers=headers,method=method) + try: + with urllib.request.urlopen(req,context=ctx,timeout=60 if path=="sys/init" and method=="PUT" else 5) as r:return json.load(r) if r.status!=204 else {} + except urllib.error.HTTPError as e: + if e.code in expect:return json.load(e) + raise RuntimeError('OpenBao request rejected: '+path+' status='+str(e.code)) from None + +def init_unseal(): + for _ in range(90): + try:status=request('GET','sys/init');break + except (OSError,RuntimeError):time.sleep(1) + else:raise RuntimeError('OpenBao TLS not ready') + p=OP/'init.json' + if not status['initialized']: + data=request('PUT','sys/init',{'secret_shares':3,'secret_threshold':2});p.write_text(json.dumps(data));os.chmod(p,0o600) + if not p.exists():raise RuntimeError('Operator unseal shares are required; never reset the persistent Bao volume') + data=json.loads(p.read_text());status=request('GET','sys/seal-status') + if status['sealed']: + for key in data['keys'][:2]:status=request('PUT','sys/unseal',{'key':key}) + assert not status['sealed'];return data['root_token'] + +def sql(text): + p=subprocess.run(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-v','ON_ERROR_STOP=1'],cwd=ROOT,input=text,text=True,capture_output=True) + if p.returncode:raise RuntimeError('Operator SQL failed (private output suppressed)') + +def configure_db(c): + statements=['REVOKE ALL ON DATABASE messenger FROM PUBLIC; REVOKE CREATE ON SCHEMA public FROM PUBLIC; REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC; REVOKE ALL ON FUNCTION auth_admit(text) FROM PUBLIC;'] + for role in ['api','worker','dispatcher','housekeeping']: + user='messenger_'+role;password=c[role]['db_password'];statements.append("DO $$ BEGIN IF NOT EXISTS(SELECT FROM pg_roles WHERE rolname='"+user+"') THEN CREATE ROLE "+user+" LOGIN; END IF; END $$; ALTER ROLE "+user+" PASSWORD '"+password+"'; GRANT CONNECT ON DATABASE messenger TO "+user+"; GRANT USAGE ON SCHEMA public TO "+user+"; REVOKE ALL ON ALL TABLES IN SCHEMA public FROM "+user+";") + statements += [ + 'GRANT SELECT,INSERT,UPDATE ON users,chats TO messenger_api;', + 'GRANT SELECT,INSERT ON chat_members,messages,message_attachments TO messenger_api;', + 'GRANT SELECT,INSERT,DELETE ON sessions,message_requests,upload_intents TO messenger_api;', + 'GRANT SELECT,INSERT,UPDATE ON attachments TO messenger_api; GRANT UPDATE(body_hash,response,expires_at) ON message_requests TO messenger_api;', + 'GRANT SELECT,INSERT ON pipeline_jobs TO messenger_api;', + 'GRANT SELECT,INSERT,UPDATE,DELETE ON auth_limits TO messenger_api; GRANT EXECUTE ON FUNCTION auth_admit(text) TO messenger_api;', + 'GRANT SELECT ON pipeline_jobs,attachments TO messenger_dispatcher; GRANT UPDATE(published_at) ON pipeline_jobs TO messenger_dispatcher;', + 'GRANT SELECT ON pipeline_jobs,attachments TO messenger_worker; GRANT UPDATE ON pipeline_jobs TO messenger_worker;', + 'GRANT UPDATE(status,error_code,variants,object_key,updated_at) ON attachments TO messenger_worker;', + 'GRANT INSERT ON pipeline_audit TO messenger_worker; GRANT USAGE ON SEQUENCE pipeline_audit_id_seq TO messenger_worker;', + 'GRANT SELECT ON attachments,upload_intents TO messenger_housekeeping; GRANT UPDATE(updated_at) ON attachments TO messenger_housekeeping; GRANT DELETE ON upload_intents TO messenger_housekeeping;' + ] + sql('\n'.join(statements)) + +def configure(root,c): + mounts=request('GET','sys/mounts',token=root) + if 'kv/' not in mounts:request('POST','sys/mounts/kv',{'type':'kv','options':{'version':'2'}},root) + auth=request('GET','sys/auth',token=root) + if 'cert/' not in auth:request('POST','sys/auth/cert',{'type':'cert'},root) + audits=request('GET','sys/audit',token=root) + assert 'file/' in audits, 'Declarative audit device must be enabled in server.hcl' + policies=ROOT/'infra/openbao/policies';policies.mkdir(exist_ok=True) + for role in ['api','worker','dispatcher','housekeeping']: + policy='path "kv/data/'+role+'" { capabilities = ["read"] }\npath "auth/token/lookup-self" { capabilities = ["read"] }\npath "auth/token/revoke-self" { capabilities = ["update"] }\n' + (policies/(role+'.hcl')).write_text(policy) + request('PUT','sys/policies/acl/'+role,{'policy':policy},root) + request('POST','auth/cert/certs/'+role,{'certificate':(ROOT/'certs/private'/role/'cert.crt').read_text(),'allowed_dns_sans':[role+'.client.lab'],'token_policies':[role],'token_no_default_policy':True,'token_ttl':60,'token_max_ttl':60},root) + data=c[role] + values={'database_url':'postgres://messenger_'+role+':'+data['db_password']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/tls/ca.crt','cache_url':'rediss://api:'+data['cache_password']+'@cache:6379/0','broker_url':'rediss://'+role+':'+data['broker_password']+'@broker:6379/0','s3_access_key_id':data['s3_access_key_id'],'s3_secret_access_key':data['s3_secret_access_key'],'cursor_key':c['cursor_key']} + allowed={'api':{'database_url','cache_url','cursor_key','s3_access_key_id','s3_secret_access_key'},'worker':{'database_url','broker_url','s3_access_key_id','s3_secret_access_key'},'dispatcher':{'database_url','broker_url'},'housekeeping':{'database_url','s3_access_key_id','s3_secret_access_key'}}[role] + values={k:v for k,v in values.items() if k in allowed} + request('POST','kv/data/'+role,{'data':values},root) + +def main(): + root=init_unseal() + if len(sys.argv)>1 and sys.argv[1]=='unseal':print('OpenBao unsealed by operator; shares/root token hidden.');return + c=json.loads((OP/'credentials.json').read_text());configure_db(c);configure(root,c) + print('Scoped DB grants, service certificate auth, TTL60s policies, KV and HMAC audit configured; no private output.') +if __name__=='__main__':main() diff --git a/scripts/bootstrap.py b/scripts/bootstrap.py new file mode 100644 index 0000000..298f41d --- /dev/null +++ b/scripts/bootstrap.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Operator-only local PKI and credentials. No private material enters Git/images.""" +import base64,json,os,secrets,subprocess,sys +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1];PRIVATE=ROOT/'certs/private';OP=ROOT/'secrets/operator' +ROLES=['api','worker','dispatcher','housekeeping','lb','cache','broker','s3','collector','prometheus','loki','tempo','grafana','openbao','operator','postgres','migrator','outsider'] +def openssl(*args): + p=subprocess.run(['openssl',*map(str,args)],capture_output=True,text=True) + if p.returncode:raise RuntimeError('openssl operation failed (private output suppressed)') +def create_ca(name): + d=OP/name;d.mkdir(parents=True,exist_ok=True,mode=0o700) + if not (d/'ca.key').exists(): + openssl('req','-x509','-newkey','ec','-pkeyopt','ec_paramgen_curve:prime256v1','-nodes','-keyout',d/'ca.key','-out',d/'ca.crt','-days','365','-subj','/CN=MTUSI lab7 '+name) + return d +def issue(role,force=False,ca_name='ca',identity=None,days=1): + identity=identity or role + ca=create_ca(ca_name);d=PRIVATE/role;d.mkdir(parents=True,exist_ok=True,mode=0o700) + if (d/'cert.crt').exists() and not force and (d/'policy-v2').exists(): + valid=subprocess.run(['openssl','x509','-in',str(d/'cert.crt'),'-noout','-checkend','300'],capture_output=True).returncode==0 + if valid:return + for old in d.iterdir(): + if old.is_file():os.chmod(old,0o600) + # Public SANs are roles/endpoints, no user data. Client authorization checks exact DNS SAN. + servers={'api','lb','cache','broker','s3','collector','prometheus','loki','tempo','grafana','openbao','postgres'} + clients={'api','worker','dispatcher','housekeeping','lb','collector','prometheus','grafana','operator','migrator','outsider','alien'} + eku=[];sans=[] + if identity in servers:eku.append('serverAuth');sans.append('DNS:'+identity) + if identity in clients:eku.append('clientAuth');sans.append('DNS:'+identity+'.client.lab') + if identity in {'lb','openbao','grafana'}:sans+=['DNS:localhost','IP:127.0.0.1'] + ext=d/'extensions.conf';ext.write_text('basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage='+','.join(eku)+'\nsubjectAltName='+','.join(sans)+'\n') + openssl('req','-new','-newkey','ec','-pkeyopt','ec_paramgen_curve:prime256v1','-nodes','-keyout',d/'new.key','-out',d/'request.csr','-subj','/CN='+identity) + openssl('x509','-req','-in',d/'request.csr','-CA',ca/'ca.crt','-CAkey',ca/'ca.key','-set_serial',str(secrets.randbits(120)),'-out',d/'new.crt','-days',str(days),'-extfile',ext) + os.replace(d/'new.key',d/'key.key');os.replace(d/'new.crt',d/'cert.crt') + (d/'ca.crt').write_bytes((OP/'ca/ca.crt').read_bytes());(d/'full.pem').write_bytes((d/'cert.crt').read_bytes()+(d/'key.key').read_bytes());(d/'request.csr').unlink();ext.unlink();(d/'policy-v2').write_text('role-specific SAN/EKU v2\n') + for p in d.iterdir():os.chmod(p,0o444) + # Compose uses root-owned bind files, non-root UID10001 reads inside its container; + # host private directories remain0700 and each service mounts only its own leaf. +def main(): + OP.mkdir(parents=True,exist_ok=True,mode=0o700);PRIVATE.mkdir(parents=True,exist_ok=True,mode=0o700) + create_ca('ca') + for role in ROLES:issue(role) + issue('alien',ca_name='alien-ca') + (ROOT/'certs/ca.crt').write_bytes((OP/'ca/ca.crt').read_bytes()) + d=ROOT/'secrets';d.mkdir(exist_ok=True,mode=0o700) + for old in d.iterdir(): + if old.is_file():os.chmod(old,0o600) + p=d/'operator/credentials.json' + if not p.exists(): + credentials={'postgres_admin':secrets.token_hex(24),'s3_root_user':'root_'+secrets.token_hex(8),'s3_root_password':secrets.token_hex(24),'grafana_password':secrets.token_hex(24),'cursor_key':base64.urlsafe_b64encode(secrets.token_bytes(32)).decode().rstrip('=')} + for role in ['api','worker','dispatcher','housekeeping']: + credentials[role]={'db_password':secrets.token_hex(24),'s3_access_key_id':'lab7_'+role,'s3_secret_access_key':secrets.token_hex(24),'broker_password':secrets.token_hex(24),'cache_password':secrets.token_hex(24)} + p.write_text(json.dumps(credentials));os.chmod(p,0o600) + else:credentials=json.loads(p.read_text()) + (OP/'s3-users.sh').write_text('\n'.join(r.upper()+'_'+k.upper()+'='+credentials[r][k] for r in ['api','worker','housekeeping'] for k in ['s3_access_key_id','s3_secret_access_key'])+'\n');os.chmod(OP/'s3-users.sh',0o600) + admin={'database_url':'postgres://messenger:'+credentials['postgres_admin']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/tls/ca.crt','s3_access_key_id':credentials['s3_root_user'],'s3_secret_access_key':credentials['s3_root_password']} + (OP/'admin-runtime.json').write_text(json.dumps(admin));os.chmod(OP/'admin-runtime.json',0o600) + for name in ['s3_root_user','s3_root_password','grafana_password']:(d/name).write_text(credentials[name]+'\n') + (d/'postgres_password').write_text(credentials['postgres_admin']+'\n') + (d/'migrate_database_url').write_text('postgres://messenger:'+credentials['postgres_admin']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/tls/ca.crt\n') + (d/'valkey_config').write_text('bind 127.0.0.1\nport 6380\nprotected-mode yes\nsave ""\nappendonly no\nuser default off\nuser api on >'+credentials['api']['cache_password']+' ~profile:* +get +set +ping +hello +client|setinfo\n') + (d/'broker_config').write_text('bind 127.0.0.1\nport 6380\nprotected-mode yes\ndir /data\nsave ""\nappendonly yes\nappendfsync always\nmaxmemory 192mb\nmaxmemory-policy noeviction\nuser default off\nuser dispatcher on >'+credentials['dispatcher']['broker_password']+' ~attachment.jobs.v1 +xadd +ping +hello +client|setinfo\nuser worker on >'+credentials['worker']['broker_password']+' ~attachment.jobs.v1 +xgroup|create +xreadgroup +xautoclaim +xack +xdel +ping +hello +client|setinfo\n') + for p in d.iterdir(): + if p.is_file():os.chmod(p,0o444) + rev=ROOT/'infra/tls/revoked.json';rev.parent.mkdir(exist_ok=True,parents=True) + if not rev.exists():rev.write_text('[]\n') + if not (ROOT/'.env').exists():(ROOT/'.env').write_text('APP_PORT=8443\nSESSION_TTL_SECONDS=3600\n') + print('Operator bootstrap complete; private values hidden; existing identities preserved.') +if __name__=='__main__':main() diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 0000000..09cedda --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +docker compose stop lb api worker dispatcher housekeeping +docker compose restart postgres openbao +docker compose restart broker cache s3 collector prometheus loki tempo grafana +# Rejoin the current owner network namespace; preserve every named volume. +docker compose up -d --no-deps --force-recreate broker-store cache-store s3-store collector-store prometheus-store loki-store tempo-store grafana-store +python3 scripts/bao_operator.py unseal +docker compose up -d --no-deps --wait api worker dispatcher housekeeping lb diff --git a/scripts/rolling.sh b/scripts/rolling.sh new file mode 100755 index 0000000..0d2f4bb --- /dev/null +++ b/scripts/rolling.sh @@ -0,0 +1,11 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +ids=$(docker compose ps -q api) +count=$(printf '%s\n' "$ids" | wc -l | tr -d ' ') +for id in $ids; do + docker stop --time 6 "$id" >/dev/null + docker rm "$id" >/dev/null + docker compose up -d --no-deps --scale api="$count" --wait api >/dev/null + sleep 2 +done diff --git a/scripts/rotate.py b/scripts/rotate.py new file mode 100644 index 0000000..af3b7d6 --- /dev/null +++ b/scripts/rotate.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""Operator rotation/revocation, no image rebuild. Values stay in ignored files.""" +import argparse,importlib.util,json,os,secrets,subprocess,time +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +def load(name): + spec=importlib.util.spec_from_file_location(name,ROOT/'scripts'/f'{name}.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m +op=load('bao_operator');boot=load('bootstrap') +def serial(role): + out=subprocess.check_output(['openssl','x509','-in',str(ROOT/'certs/private'/role/'cert.crt'),'-noout','-serial'],text=True) + return out.strip().split('=',1)[1].lower().lstrip('0') or '0' +def revoke(role): + p=ROOT/'infra/tls/revoked.json';values=json.loads(p.read_text());values.append(serial(role));p.write_text(json.dumps(sorted(set(values)))+'\n') +def rotate(role,certificate=True): + c=json.loads((op.OP/'credentials.json').read_text());root=json.loads((op.OP/'init.json').read_text())['root_token'] + if certificate:revoke(role);boot.issue(role,force=True) + c[role]['db_password']=secrets.token_hex(24) + (op.OP/'credentials.json').write_text(json.dumps(c));os.chmod(op.OP/'credentials.json',0o600) + # New connections reject old passwords; terminate existing sessions explicitly. + op.sql("ALTER ROLE messenger_"+role+" PASSWORD '"+c[role]['db_password']+"'; SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='messenger_"+role+"' AND pid<>pg_backend_pid();") + op.configure(root,c) + print('Rotated '+role+' SQL secret'+(' and leaf certificate; previous serial denied' if certificate else '')+'; images unchanged; private values hidden.') +def main(): + p=argparse.ArgumentParser();p.add_argument('action',choices=['revoke','rotate','secret']);p.add_argument('role',choices=['api','worker','dispatcher','housekeeping']);args=p.parse_args() + if args.action=='revoke': + revoke(args.role);root=json.loads((op.OP/'init.json').read_text())['root_token'];op.request('DELETE','auth/cert/certs/'+args.role,token=root);print('Revoked service serial and OpenBao certificate authentication.') + else:rotate(args.role,args.action=='rotate') +if __name__=='__main__':main() diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 0000000..e0dcd74 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,13 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +: "${TARGET_INSTANCE_ID:?required API alias}" +for id in $(docker compose ps -q api); do + alias=$(docker exec "$id" cat /run/runtime/instance_alias) + if [ "$alias" = "$TARGET_INSTANCE_ID" ]; then + docker stop --time 6 "$id" >/dev/null + exit 0 + fi +done +printf '%s\n' 'Target API instance is not running' >&2 +exit 1 diff --git a/scripts/up.py b/scripts/up.py new file mode 100644 index 0000000..b516a68 --- /dev/null +++ b/scripts/up.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +import os,ssl,subprocess,time,urllib.request +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +def run(*args):subprocess.run(args,cwd=ROOT,check=True) +run('python3','scripts/bootstrap.py') +run('docker','compose','build','api') +run('docker','compose','up','-d','--no-build','--force-recreate') +# API depends_on service_completed_successfully already gates migrations. +ids=subprocess.check_output(['docker','compose','ps','-a','-q','migrate'],cwd=ROOT,text=True).splitlines() +assert ids, 'migration container missing' +for cid in ids: + result=subprocess.check_output(['docker','inspect','--format','{{.State.ExitCode}}',cid],text=True).strip();assert result=='0', 'migration failed' +run('python3','scripts/bao_operator.py') +ctx=ssl.create_default_context(cafile=str(ROOT/'certs/ca.crt')) +port=os.environ.get('APP_PORT','8443') +for _ in range(90): + try: + with urllib.request.urlopen('https://localhost:'+port+'/health/ready',context=ctx,timeout=2) as r: + if r.status==200:print('HTTPS/mTLS application ready; certificate verification enabled.');break + except OSError:pass + time.sleep(1) +else:raise RuntimeError('Secure ingress did not become ready') diff --git a/security/SCAN_TRIAGE.md b/security/SCAN_TRIAGE.md new file mode 100644 index 0000000..cee54da --- /dev/null +++ b/security/SCAN_TRIAGE.md @@ -0,0 +1,24 @@ +# Разбор dependency scan + +2 декабря2026. Реальный govulncheck1.10.0, Go1.27.4, база https://vuln.go.dev modified2026-11-24. До обновления библиотек:423 findings (несколько путей/уровней на один advisory),24 distinct called Go advisories. После обновления:0 findings. Это не423 уникальные CVE и не сертификат отсутствия всех ошибок. + +```sh +docker run --rm -v "$PWD:/src" -w /src golang:1.27.4-alpine3.24 \ + sh -c 'go run golang.org/x/vuln/cmd/govulncheck@v1.10.0 -format json ./...' +gzip -dc evidence/dependency-scan-initial.json.gz +gzip -dc evidence/dependency-scan.json.gz +``` + +Воспроизводимость версий обеспечивает go.mod/go.sum; network скачивает публичные зависимости/базу. Summary хранит config самого scanner, IDs, summaries и primary advisory links. Старый toolchain1.24.4 заменён1.27.4; initial scan в evidence уже использует новый Go и прежние библиотеки. Незавершённый старый scanner run не выдаётся за полный результат. + +| Группа из реального initial scan | Применимость к стенду | Действие | +|---|---|---| +| x/image TIFF/BMP/palette: GO-2023-1572/1989/1990, GO-2024-2937, GO-2026-4815/5031/5032/5062/5066 | Imaging регистрирует дополнительные decoders, call graph видит путь. Внешний upload допускает только PNG/JPEG, проверяет bytes/pixels/full decode; worker проверяет checksum. Эти gates уменьшают доступность TIFF пути, но не заменяют исправление decoder | x/image0.45.0, runtime CPU/RAM/deadline; PNG/JPEG/EXIF/alpha tests | +| pgx GO-2026-5004 | SQL dollar-quoted/placeholder parser находится в достижимой библиотеке. Пользовательские значения передаются параметрами, шаблоны SQL фиксированы, но широкий waiver «у нас параметризация» не использован | pgx5.9.2 и real PG/concurrent HTTP tests | +| OTel resource PATH GO-2026-4394 | Старый SDK способен запускать команды детектирования через PATH. Writable PATH в app не задан, root FS read-only, UID10001 — дополнительные барьеры | SDK1.47.0; worker/app privileges уменьшены | +| OTel body/allocation/logging/busy-spin GO-2026-4985/5506/6505/6615/6974 | Telemetry exporters реально работают. Endpoints без credentials в URL, payload не логируется; доверенный backend всё равно может быть повреждён. Queue/memory limits ограничивают ущерб, не исправляют библиотеку | SDK/exporters1.47.0, log exporter0.23.0, otelslog0.21.0; actual TLS trace/log/Grafana queries | +| x/net HTTP2 и grpc GO-2026-6603/6611/6612/6617/6061/6348 | Часть серверных путей не опубликована приложением напрямую, native gRPC у telemetry loopback. Call graph conservative; сетевой доступ через проверенные gateways, всё равно обновлено | Совместимые новые x/net/grpc из go.mod; Go1.27.4 | +| x/text GO-2026-5970/6629 | Unicode/precis code достижим транзитивно; bytes/request bounds уменьшают размер input, не доказывают невозможность panic/loop | Обновлён x/text через согласованные OTel/x/crypto dependencies | +| Прочие module/package-level findings compress/x/sys/x/crypto | Не каждый advisory имеет reachable application symbol; используются те же зависимости для S3/signing/IO | Все отмеченные модули обновлены; повторный scanner0findings | + +Ограничения: это dependency/call-graph анализ Go source. Он не сканирует все OS packages и бинарники PG/MinIO/Valkey/Collector/Grafana. Закреплённые версии контейнеров не означают отсутствие CVE; их обновление требует отдельного compatibility/image scan. TLS gateways и policies проверены негативными сценариями, полноценный независимый pentest не выполнялся. Список найденных/устранённых advisories и применимость изложены вместо одного screenshot с числом CVE. diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 31da287..a902a1a 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -1,19 +1,33 @@ -# Модель угроз — заполнить +# ЛР7: модель угроз -## Активы и акторы +Автор: Крайкин Глеб Алексеевич, БВТ2303. Учебный стенд с синтетическими данными, один Docker Desktop host. Активы: пароли и сессии, сообщения, исходники/варианты изображений, задания, SQL/S3/broker credentials, закрытые ключи сервисов, CA и операторские материалы OpenBao, логи/метрики/трассы. -TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. +Акторы: внешний неавторизованный клиент, участник чата, посторонний пользователь с действующей сессией, узел внутри контейнерной сети, обладатель украденных credentials worker, оператор. Атакующий в исследовании получает копию рабочего сертификата/ключа и credentials worker, но не root/Docker socket на host, CA, операторские root/unseal shares или ключи API. Уязвимость ядра/гипервизора, физический доступ, администратор host и скомпрометированный CA вне доказанной модели. -## Границы доверия +Сеть контейнеров сама по себе не считается доказательством identity. Для межконтейнерного трафика проверяются TLS цепочка/срок/server SAN; mTLS дополнительно проверяет клиента. API и TLS gateways проверяют точный client DNS SAN вида `worker.client.lab`, а не просто подпись CA. Таблица всех связей — [TRUST_MATRIX.md](TRUST_MATRIX.md), заполненные доказательства также в contracts/trust-matrix.md. -TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. +| Угроза / конкретный путь | Контроль | Реальная отрицательная проверка | Остаточная граница | +|---|---|---|---| +| Перехват Basic/Bearer на клиент→LB | Только HTTPS, CA+hostname, TLS≥1.2 | public test-security; wrong CA/hostname | Доверенный/скомпрометированный клиент видит свой секрет | +| Узел с сертификатом worker притворяется LB и обходит ingress | API требует mTLS и exact SAN lb.client.lab, прямых host API ports нет | Каждая API: no cert / alien CA / outsider same CA → TLS refusal | Оператор CA способен выпускать разрешённые identities | +| Сертификат того же CA даёт произвольный доступ к очереди/телеметрии | Allowlist SAN + Valkey command/key ACL + HTTP method/path rules | Broker/Collector wrong identity, worker XADD/FLUSHALL/other key denied | Законные worker stream operations можно использовать во вред pipeline | +| Чужой участник читает/прикрепляет файл другого чата | PostgreSQL membership перед metadata/download/message link | Чужие metadata/content/link404, forged X-User-Id не меняет Bearer | Компрометация самого API шире прав обычного пользователя | +| Украденный worker SQL password раскрывает password/session/message tables | Отдельные LOGIN роли; worker получает pipeline grants и ограниченные UPDATE columns | SELECT users/sessions/messages, owner UPDATE, DROP →42501 | Worker может портить разрешённые metadata/status и обрабатывать все images; per-job credentials нет | +| Worker использует S3 root privileges | Разные S3 users и prefix policies | Рабочий staging HEAD разрешён; staging PUT/private prefix/bucket admin запрещены | Worker читает staging/originals всех чатов и пишет final originals prefix | +| Worker читает чужие секреты или меняет OpenBao policy | Certificate auth, exact pinned leaf, policy own kv/data path, short token TTL | Own read, чужой path/policy/sys raw forbidden; wrong role cert login denied | Статический SQL/S3 secret сам не истекает по TTL токена; требуется явная ротация | +| Дорогие login исчерпывают RAM/CPU двух API | Общие PG rate counters + не более2 Argon2 calls/API + body/header bounds | Две API:429/Retry-After, измеренный KDF budget; rehash integration | Fixed windows допускают двойной burst на границе; distributed attacker может исчерпать общий auth budget | +| Сервис продолжает работу бесконечно после sealed/revoked OpenBao | Авторизация последнего чтения имеет60s budget; refresh5s; затем child останавливается | Sealed+restart API, конечный503, unseal→тот же token/file | До deadline действует ограниченный cache; availability зависит от одного Bao | +| Украденная identity сохраняется после incident | Serial denylist, cert-auth deletion, explicit token revoke, SQL ALTER PASSWORD+terminate sessions; quarantine/replacement worker | Старый cert к broker/S3 denied, старый SQL secret с новым cert denied, все accepted files ready | Existing raw stream connection≤30s, начатый HTTP request≤35s; host/root/новый implant не моделировались | +| Секрет попадает в Git/image/logs | .gitignore/.dockerignore, per-service mounts, tmpfs, generic errors, HMAC Bao audit | Скан exact private values, image env/paths and telemetry checks | Runtime process с разрешённым доступом видит свои secrets | -| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | -| --- | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | TODO | +## Локальные границы plaintext -На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. +Для брокера/cache/S3/Collector/Prometheus/Loki/Tempo/Grafana используется TLS gateway. Native service живёт **в том же network namespace**, слушает только127.0.0.1. Шлюз слушает контейнерную сеть и разрешает клиента/действие. Native порт не публикуется и не слушает0.0.0.0: знание номера порта не даёт обхода. Gateway и native процесс входят в одну доверенную boundary; компрометация этой boundary раскрывает её локальный трафик. У PostgreSQL и OpenBao native TLS. Внутренний API health на127.0.0.1:8081 принимает только два health routes. -## Lifecycle и инциденты +## Хранение и отзыв -TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. +CA private key, root token и3 shares (порог2) находятся в ignored `secrets/operator/` с0700/0600 на host, не монтируются в OpenBao/API/worker. Leaf identities лежат в ignored `certs/private//`, каждая runtime служба видит только свою; операторский verify-profile имеет расширенные mounts явно для тестирования. Это локальная защита от других host users и компрометации service container, не внешний HSM/KMS. Shares находятся у одного учебного оператора; организационное разделение держателей не заявляется. + +Оператор выполняет init/unseal. После рестарта Bao требуется явный `make unseal`; API самостоятельно не может открыть Bao. Service auth использует24h leaf, scoped token60s; каждые5s выполняется повторная аутентификация и чтение, использованный token отзывается. Это renewal через повторный вход, а не бесконечное продление одного токена. Последнее успешное чтение допускается использовать до60s; после истечения runtime child останавливается. Leaf обновляется оператором; `make up` перевыпускает истекающие leaves и пересоздаёт процессы, CA автоматически не меняется. + +После компрометации старый процесс сначала останавливается. Затем отзываются serial и certificate auth/token, меняется SQL password с завершением прежних SQL connections, выдаётся новый leaf, worker создаётся заново из того же immutable image. Выдача новых credentials скомпрометированному живому процессу не считалась бы исправлением инцидента. diff --git a/security/TRUST_MATRIX.md b/security/TRUST_MATRIX.md new file mode 100644 index 0000000..f14a209 --- /dev/null +++ b/security/TRUST_MATRIX.md @@ -0,0 +1,37 @@ +# Фактические границы TLS и прав + +CA создаёт оператор. Все server endpoints проверяются по CA и DNS SAN, TLS≥1.2. Client SAN — `.client.lab`. Leaf24h, service auth token60s, last-success authorization cache60s, re-auth/read каждые5s. Private values не приведены. `student-tests/security.py` выполняет positive/negative tests; `sealed.py` и `compromise.py` — lifecycle. + +| Соединение | Endpoint и server identity | Client identity / разрешение | +|---|---|---| +| REST клиент→LB | https://localhost:8443, SANlocalhost | Внешний client cert не нужен; Basic только для входа, Bearer для business ACL | +| LB→каждая API | https://api:8080, SANapi | Обязательный exact SANlb.client.lab; worker/outsider/no-cert/alien CA denied | +| API/worker/dispatcher/housekeeping→PG | postgres:5432, native TLS verify-full, SANpostgres | SCRAM + отдельные messenger_api/worker/dispatcher/housekeeping; публичный plain TCP отвергается pg_hba; роли без CREATE/SUPERUSER/CREATEROLE | +| API/worker/housekeeping→S3 | https://s3:9000, SANs3 | mTLS exact api/worker/housekeeping; разные S3 users; api staging PUT/delete и final GET, worker staging/final GET и final PUT, housekeeping staging list/delete | +| Dispatcher/worker→broker | rediss broker:6379, SANbroker | mTLS dispatcher/worker; producer XADD только attachment.jobs.v1; consumer XGROUP CREATE/XREADGROUP/XAUTOCLAIM/XACK/XDEL только тот же key | +| API→broker | N/A | API пишет PG outbox, не подключается к broker; нет обхода dispatcher | +| API→cache | rediss cache:6379, SANcache | mTLS api, ACL только GET/SET profile:* и handshake/ping; cache fail→PG, ACL не берётся из cache | +| API/worker/dispatcher/housekeeping→Collector | https://collector:4318, SANcollector | Раздельные mTLS identities; POST только /v1/traces/logs/metrics | +| Collector→Loki | https://loki:3100/otlp/v1/logs, SANloki | Только collector mTLS + POST ingestion; Grafana не может ingest | +| Collector→Tempo | https://tempo:4318/v1/traces, SANtempo | Только collector mTLS + POST ingestion | +| Prometheus→Collector metrics | https://collector:8889/metrics и8888/metrics | mTLS prometheus, только GET/metrics | +| Prometheus→LB metrics | https://lb:8404/metrics, SANlb | mTLS + доверенная identity/CNprometheus; port не опубликован | +| Grafana→Prometheus | https://prometheus:9090, SANprometheus | mTLS grafana; только query/labels/series/metadata/buildinfo paths, admin API запрещён | +| Grafana→Loki | https://loki:3100, SANloki | mTLS grafana; только GET query/labels/series/index/buildinfo | +| Grafana→Tempo | https://tempo:3200, SANtempo | mTLS grafana; GET /api/* и /ready; нет ingestion port | +| Сервисы→OpenBao | https://openbao:8200, SANopenbao | TLS server + certificate auth pinned leaf/SAN; policy только own kv/data path и own token lookup/revoke | +| Оператор→Bao | https://localhost:8207, SANlocalhost | Root token/shares только у host оператора; port loopback; TLS trust обязателен | +| Оператор→Grafana | https://localhost:3007, SANlocalhost | TLS и случайный admin password; anonymous отключён | +| Оператор→S3 | https://s3:9000 через verify-profile | mTLSoperator и S3 admin auth; host S3 console/data ports отсутствуют. Начальный mc job в закрытом S3 namespace с root только на время provisioning | +| Health | API127.0.0.1:8081, native backend loopback | Только local boundary; API health handler не маршрутизирует business endpoints | +| Replication/cluster | Только один Raft voter, один instance прочих stores | Межузловых replication channels нет. OpenBao cluster protocol штатно использует собственный TLS; multi-node HA не заявляется | + +## Права SQL + +`messenger_api` читает credentials для проверки login и данные для ACL, пишет business records; не владеет schema и не может создавать роли/таблицы. `messenger_worker` читает только attachments/pipeline_jobs, меняет execution fields и status/variants/object_key/updated_at, добавляет audit. Не меняет owner_id/chat_id/sha256 исходника; не читает users/sessions/messages. `messenger_dispatcher` читает очередь и attachment status, меняет только published_at. `messenger_housekeeping` читает staging metadata/intents, удаляет intents, имеет UPDATE(updated_at) для SQL row locking. Политики и grants — scripts/bao_operator.py. + +Migrate — отдельный операторский одноразовый процесс с владельцем schema, не runtime API. Stateful root FS read-only где совместимо; PG entrypoint временно имеет CHOWN/FOWNER/DAC_OVERRIDE/SETUID/SETGID, затем native postgres выполняется своим UID. Storage init имеет только CHOWN/DAC_OVERRIDE для named volumes и заканчивает работу. Runtime API/worker/gateways UID10001, capabilities ALL dropped, no-new-privileges, tmpfs и CPU/RAM limits. У native stores named volumes остаются writable. + +## Проверяемые пределы отзыва + +Новый TLS handshake проверяет цепочку, срок, exact SAN и актуальный revoked serial; resumption у gateway отключён. HTTP повторно проверяет identity/serial на каждом запросе, уже начатый запрос ограничен35s. Raw Valkey connection имеет абсолютный30s deadline; после reconnect revoked cert отклоняется. SQL rotation отдельно прекращает существующие sessions. Новый leaf читается при новом client/server handshake без rebuild; supervisor повторно запускает child при изменении secrets. Это bounded revocation с явно названными границами, не мгновенное стирание уже переданных данных. diff --git a/student-tests/clean_clone.py b/student-tests/clean_clone.py new file mode 100644 index 0000000..6c5141c --- /dev/null +++ b/student-tests/clean_clone.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""Committed lab7, truly new clone/CA/credentials/volumes, explicit operator restart.""" +import json,os,socket,subprocess,tempfile,uuid +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +def free(): + with socket.socket() as s:s.bind(('127.0.0.1',0));return str(s.getsockname()[1]) +project='verify-lab7-'+uuid.uuid4().hex[:10] +with tempfile.TemporaryDirectory(prefix=project+'-') as directory: + clone=Path(directory)/'repo';subprocess.run(['git','clone','--no-hardlinks',str(ROOT),str(clone)],check=True) + env=dict(os.environ,COMPOSE_PROJECT_NAME=project,APP_PORT=free(),GRAFANA_PORT=free(),BAO_PORT=free(),SESSION_TTL_SECONDS='3600') + base='https://localhost:'+env['APP_PORT'];ca=str(clone/'certs/ca.crt') + def run(*args):subprocess.run(args,cwd=clone,env=env,check=True) + def dc(*args):return subprocess.check_output(['docker','compose',*args],cwd=clone,env=env,text=True).strip() + def snapshot(): + result={} + for id in dc('ps','-q').splitlines(): + v=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0];result[v['Name']]={'service':v['Config']['Labels']['com.docker.compose.service'],'started_at':v['State']['StartedAt'],'user':v['Config']['User'],'image_id':v['Image'],'pid1':v['Path']} + return result + try: + run('make','up');run('make','check');run('make','test','BASE_URL='+base,'CA_FILE='+ca);run('make','test-security','BASE_URL='+base,'CA_FILE='+ca) + before=snapshot();run('make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+base,'CA_FILE='+ca);after=snapshot() + for name,item in before.items():assert after[name]['started_at']!=item['started_at'],name+' not restarted' + for item in after.values(): + if item['service'] in ['api','worker','dispatcher','housekeeping']:assert item['user']=='10001:10001' and item['pid1']=='/usr/local/bin/messenger' + request=json.dumps({'Kind':'http','Cert':'operator','URL':'https://grafana:3000/api/dashboards/uid/messenger-lab7','Auth':'grafana','ReturnBody':True}) + probe=subprocess.run(['docker','compose','--profile','verify','run','--rm','--no-deps','-T','probe'],cwd=clone,env=env,input=request,capture_output=True,text=True,check=True) + dashboard=json.loads(probe.stdout);assert dashboard['ok'];dashboard=json.loads(dashboard['body'])['dashboard'];assert len(dashboard['panels'])==24 + (ROOT/'evidence/persistence-processes.json').write_text(json.dumps({'scope':'disposable real clean clone; fresh CA, secrets and every volume','before':before,'after':after,'fresh_grafana_panels':len(dashboard['panels'])},indent=2)+'\n') + print('PASS: real clean clone, independent CA/secrets/volumes, verified HTTPS, full store/API restart, same session/file, non-root PID1, fresh Grafana provisioning') + finally: + # This unique synthetic project only. Working lab7 and unrelated volumes survive. + run('docker','compose','down','-v','--remove-orphans') diff --git a/student-tests/compromise.py b/student-tests/compromise.py new file mode 100644 index 0000000..672c31b --- /dev/null +++ b/student-tests/compromise.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Grade5 track1: copied worker credentials, bounded probes, quarantine/revoke/recover.""" +import concurrent.futures,importlib.util,json,os,shutil,subprocess,sys,threading,time,urllib.parse,uuid +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'));from client import Client,check +s=importlib.util.spec_from_file_location('sec',ROOT/'student-tests/security.py');sec=importlib.util.module_from_spec(s);s.loader.exec_module(sec) +s=importlib.util.spec_from_file_location('rot',ROOT/'scripts/rotate.py');rot=importlib.util.module_from_spec(s);s.loader.exec_module(rot) +op=rot.op;BASE=sec.BASE + +def main(): + c=Client(BASE,ca_file=sec.CA);a,b,outsider,chat=c.bootstrap();result={'model':'exfiltrated live worker leaf+service credentials, no host/Docker/CA compromise; operator probes use only selected worker identity; baseline is a deliberately overprivileged test fixture, never mounted into runtime worker','images_before':sec.dc('images','-q','worker').splitlines()} + raw=sec.dc('exec','-T','worker','cat','/run/runtime/active.json');active=json.loads(raw) + db=urllib.parse.urlparse(active['database_url']);broker=urllib.parse.urlparse(active['broker_url']) + stolen={'worker':{'db_password':db.password,'broker_password':broker.password,'s3_access_key_id':active['s3_access_key_id'],'s3_secret_access_key':active['s3_secret_access_key']}} + (op.OP/'stolen-worker.json').write_text(json.dumps(stolen));os.chmod(op.OP/'stolen-worker.json',0o600) + d=ROOT/'certs/private/stolen-worker' + if d.exists():shutil.rmtree(d) + shutil.copytree(ROOT/'certs/private/worker',d) + defaults={'Role':'worker','Cert':'stolen-worker','CredentialsFile':'/operator/stolen-worker.json'} + probe=lambda **kw:sec.probe(**dict(defaults,**kw)) + # A pre-separation model with API SQL credentials/root S3 credentials allows broader access. + broad=json.loads((op.OP/'credentials.json').read_text());broad['baseline']={'s3_access_key_id':broad['s3_root_user'],'s3_secret_access_key':broad['s3_root_password']};(op.OP/'baseline-worker.json').write_text(json.dumps({'baseline':broad['baseline']}));os.chmod(op.OP/'baseline-worker.json',0o600) + result['before_least_privilege']={'password_table':sec.probe(Kind='postgres',Role='api',Cert='stolen-worker',Query='SELECT password_hash FROM users LIMIT 1'),'bucket_administration':sec.probe(Kind='s3',Role='baseline',Cert='stolen-worker',CredentialsFile='/operator/baseline-worker.json',Method='LIST_BUCKETS')} + assert all(x['ok'] for x in result['before_least_privilege'].values()) + sec.dc('stop','worker') # quarantine before new secrets become visible to replacement + att,data=c.attachment(a,chat);accepted=[(att,data)] + stage=sec.sql_value("SELECT staging_key FROM attachments WHERE id='"+att['id']+"'") + marker='originals/security-probe-'+uuid.uuid4().hex+'/marker' + good={'db_pipeline':probe(Kind='postgres',Query='SELECT job_id FROM pipeline_jobs LIMIT 1'),'db_execution_update':probe(Kind='postgres',Query="UPDATE attachments SET status=status WHERE id='"+att['id']+"'"),'s3_staging':probe(Kind='s3',Key=stage),'s3_final_put':probe(Kind='s3',Method='PUT',Key=marker,Body='synthetic allowed scope'),'queue_ping':probe(Kind='redis',Command=['PING'])} + assert all(x['ok'] for x in good.values()),good + denied={} + for name,query in [('password_table','SELECT password_hash FROM users'),('sessions','SELECT token_hash FROM sessions'),('messages','SELECT text FROM messages'),('change_owner',"UPDATE attachments SET owner_id=owner_id WHERE false"),('change_checksum',"UPDATE attachments SET sha256=sha256 WHERE false"),('drop_table','BEGIN; DROP TABLE users; ROLLBACK;')]: + denied[name]=probe(Kind='postgres',Query=query);assert not denied[name]['ok'] and denied[name].get('error_category')=='permission_denied',(name,denied[name]) + for name,args in [('s3_private_prefix',{'Kind':'s3','Method':'PUT','Key':'private/blocked','Body':'synthetic'}),('s3_staging_write',{'Kind':'s3','Method':'PUT','Key':'staging/blocked','Body':'synthetic'}),('s3_final_delete',{'Kind':'s3','Method':'DELETE','Key':marker}),('bucket_administration',{'Kind':'s3','Method':'LIST_BUCKETS'}),('queue_publish',{'Kind':'redis','Command':['XADD','attachment.jobs.v1','*','payload','{}']}),('queue_flush',{'Kind':'redis','Command':['FLUSHALL']}),('queue_other_key',{'Kind':'redis','Command':['XREADGROUP','GROUP','image-workers','probe','STREAMS','other.stream','>']})]: + denied[name]=probe(**args);assert not denied[name]['ok'] and denied[name].get('error_category')=='permission_denied',(name,denied[name]) + login=op.request('POST','auth/cert/login',{'name':'worker'},cert='worker')['auth'];oldtoken=login['client_token'];accessor=login['accessor'] + try:op.request('GET','kv/data/api',token=oldtoken,cert='worker') + except RuntimeError:denied['bao_api_secret']={'ok':False,'error_category':'policy_denied'} + else:raise AssertionError('worker read API secret') + for _ in range(7):accepted.append(c.attachment(a,chat)) + result['accepted_while_quarantined']=len(accepted);result['least_privilege']={'allowed':good,'denied':denied} + stop=threading.Event();traffic=[] + def send(): + client=Client(BASE,ca_file=sec.CA) + while not stop.is_set(): + try:client.message(a,chat,'Synthetic during worker revocation');traffic.append(True) + except Exception:traffic.append(False) + time.sleep(.05) + pool=concurrent.futures.ThreadPoolExecutor(2);tasks=[pool.submit(send) for _ in range(2)] + start=time.monotonic();root=json.loads((op.OP/'init.json').read_text())['root_token'] + try: + rot.revoke('worker');op.request('DELETE','auth/cert/certs/worker',token=root);op.request('POST','auth/token/revoke-accessor',{'accessor':accessor},root) + after={} + after['old_cert_queue']=probe(Kind='redis',Command=['PING']);after['old_cert_s3']=probe(Kind='s3',Key=stage) + assert not after['old_cert_queue']['ok'] and not after['old_cert_s3']['ok'] + try:op.request('GET','kv/data/worker',token=oldtoken,cert='stolen-worker') + except RuntimeError:after['old_bao_token_denied']=True + else:raise AssertionError('revoked Bao token accepted') + rot.rotate('worker',certificate=True) + # Use a NEW accepted TLS identity to prove the old SQL password itself is revoked. + after['old_sql_password']=probe(Kind='postgres',Cert='worker',Query='SELECT 1');assert not after['old_sql_password']['ok'] and after['old_sql_password'].get('error_category')=='credential_denied' + sec.dc('up','-d','--no-deps','--force-recreate','worker') + for attachment,original in accepted: + ready=c.wait_ready(a,attachment);download=c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=a);check(download['bytes']==original,'accepted original changed') + elapsed=time.monotonic()-start;result['after_revocation']=after + finally:stop.set();pool.shutdown(wait=True) + result.update(recovery_all_ready_seconds=round(elapsed,3),all_accepted_originals_identical=True,background_messages_success=sum(traffic),background_messages_errors=len(traffic)-sum(traffic),images_after=sec.dc('images','-q','worker').splitlines(),new_worker_connects=sec.probe(Kind='redis',Role='worker',Cert='worker',Command=['PING'])) + assert result['images_before']==result['images_after'] and result['new_worker_connects']['ok'] + (ROOT/'evidence/worker-compromise.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: bounded worker compromise, before/after least privilege, actual identity/SQL revocation, fresh worker restored all accepted bytes; no image rebuild',flush=True) +if __name__=='__main__':main() diff --git a/student-tests/hardening.py b/student-tests/hardening.py new file mode 100644 index 0000000..ac3a19d --- /dev/null +++ b/student-tests/hardening.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Inspect actual runtime controls; verify no native plaintext bypass or leakage.""" +import importlib.util,json,os,subprocess,time +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +s=importlib.util.spec_from_file_location('sec',ROOT/'student-tests/security.py');sec=importlib.util.module_from_spec(s);s.loader.exec_module(sec) +def main(): + rows=[];sensitive=[] + credentials=json.loads((ROOT/'secrets/operator/credentials.json').read_text());sensitive += [credentials['postgres_admin'],credentials['s3_root_password'],credentials['cursor_key']] + for role in ['api','worker','dispatcher','housekeeping']:sensitive += [credentials[role][k] for k in ['db_password','broker_password','cache_password','s3_secret_access_key']] + material=json.loads((ROOT/'secrets/operator/init.json').read_text());sensitive += [material['root_token'],*material['keys']] + apps={'api','worker','dispatcher','housekeeping','broker','cache','s3','collector','prometheus','loki','tempo','grafana'} + for id in sec.dc('ps','-q').splitlines(): + item=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0];name=item['Config']['Labels']['com.docker.compose.service'];host=item['HostConfig'] + assert not host['Privileged'] and host['NetworkMode']!='host' + assert not any('docker.sock' in m['Source'] or m['Destination']=='/operator' for m in item['Mounts']) + assert not any(value in json.dumps(item['Config'].get('Env',[])) for value in sensitive) + if name in apps: + assert item['Config']['User']=='10001:10001' and host['ReadonlyRootfs'] and 'ALL' in host['CapDrop'] and 'no-new-privileges:true' in host['SecurityOpt'] + for bindings in (host.get('PortBindings') or {}).values(): + for b in bindings or []:assert name in ['lb','openbao','grafana'] and b['HostIp']=='127.0.0.1' + rows.append({'service':name,'user':item['Config']['User'],'read_only':host['ReadonlyRootfs'],'drop_capabilities':host['CapDrop'],'add_capabilities':host['CapAdd'],'security_options':host['SecurityOpt'],'memory_limit_bytes':host['Memory'],'nano_cpus_limit':host['NanoCpus'],'image_id':item['Image'],'started_at':item['State']['StartedAt'],'published_ports':host.get('PortBindings')}) + denied=[] + for service,port in [('api',8081),('broker',6380),('cache',6380),('s3',9001),('s3',9002),('collector',4319),('collector',8890),('prometheus',9091),('loki',3101),('tempo',3201),('grafana',3001)]: + r=sec.probe(Kind='http',URL='https://'+service+':'+str(port)+'/health/ready',Cert='operator') + assert not r['ok'] and r.get('error_category')=='connection_or_action_denied',(service,port,r) + denied.append({'service':service,'native_port':port,'external_namespace_connection_denied':True}) + # Worker cannot mutate rootfs or read operator/other-role material. + filesystem={} + for name,command in [('rootfs_write',['touch','/unauthorized-file']),('operator_key',['cat','/operator/init.json']),('other_identity',['cat','/run/tls/lb/key.key'])]: + p=subprocess.run(['docker','compose','exec','-T','worker',*command],cwd=ROOT,capture_output=True);assert p.returncode!=0;filesystem[name]='denied' + logs=sec.dc('logs','--no-color','--tail','500','api','worker','dispatcher','collector-store') + assert not any(v in logs for v in sensitive) + status=sec.dc('exec','-T','worker','cat','/proc/1/status');assert 'CapEff:\t0000000000000000' in status and 'NoNewPrivs:\t1' in status + result={'runtime':rows,'no_native_bypass':denied,'worker_filesystem':filesystem,'worker_effective_caps_zero':True,'worker_no_new_privileges':True,'known_private_values_absent_from_config_env_and_sampled_logs':True,'scope':'runtime containers only; verify-profile compiler/operator tools not persistent runtime; last500 app/collector log lines sampled, not proof of all future logs'} + (ROOT/'evidence/hardening.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: actual non-root/capabilities/read-only/ports, closed native hops, scoped worker mounts and sampled private-value scan',flush=True) +if __name__=='__main__':main() diff --git a/student-tests/ingress_guard.py b/student-tests/ingress_guard.py new file mode 100644 index 0000000..6743053 --- /dev/null +++ b/student-tests/ingress_guard.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +"""Prove the SLI also observes a 503 generated by HAProxy, outside API SDKs.""" +import json,time,urllib.request,urllib.error +from observability import ROOT,BASE,Client,check,dc,scalar,wait_for +c=Client(BASE);a,b,e,chat=c.bootstrap();before=scalar('sum(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"})') or 0 +try: + dc('stop','api');time.sleep(2) + req=urllib.request.Request(BASE+'/api/v1/users/me',headers={'Authorization':'Bearer '+a['token']}) + try:response=urllib.request.urlopen(req,timeout=4) + except urllib.error.HTTPError as error:response=error + with response:check(response.code==503,'expected LB 503');status=response.code + after,delay=wait_for(lambda: (lambda n:n if n is not None and n>before else None)(scalar('sum(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"})')),15) + result={'client_status':status,'api_processes_stopped':True,'ingress_5xx_before':before,'ingress_5xx_after':after,'observation_seconds':delay,'lb_generated_error_counted':True} + (ROOT/'evidence/ingress-guard.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: LB-generated 503 included in business ingress SLI') +finally:dc('up','-d','--no-deps','--wait','api') +c.call('GET','/api/v1/users/me',actor=a,schema='User') diff --git a/student-tests/operations.py b/student-tests/operations.py new file mode 100644 index 0000000..920cc93 --- /dev/null +++ b/student-tests/operations.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Stop each real container, then replace them in sequence under writes.""" +import json,os,subprocess,sys,threading,time,uuid +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'tests')) +from client import Client,Failure,check +BASE=os.environ.get('BASE_URL','https://localhost:8443') +def dc(*args):return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip() +def inspect(id):return json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0] +def ready(): + deadline=time.monotonic()+45 + while time.monotonic()=action_done] + check(successes_after,'no successful write after action') + recovery=successes_after[0]-started + return {'successful_writes':len(results),'errors':failed,'successful_rps':len(results)/(time.monotonic()-started+1),'first_recovery_seconds':round(recovery,3),'action_seconds':round(action_done-started,3),'instances':sorted(seen),'confirmed_preserved':True} +def main(): + ready();c=Client(BASE,ca_file=str(ROOT/'certs/ca.crt'));a,b,e,chat=c.bootstrap();results={'failures':[]} + ids=dc('ps','-q','api').splitlines();check(len(ids)==2,'requires two API containers') + for id in ids: + alias=subprocess.check_output(['docker','exec',id,'cat','/run/runtime/instance_alias'],text=True).strip() + env=dict(os.environ,TARGET_INSTANCE_ID=alias) + def action():subprocess.run([str(ROOT/'scripts/stop-one.sh')],env=env,check=True,stdout=subprocess.DEVNULL) + try: + result=run_phase(c,a,chat,action);result['stopped_alias']=alias + check(not inspect(id)['State']['Running'],'target is still running') + check(result['first_recovery_seconds']<10,'recovery >10s') + results['failures'].append(result) + finally:ready() + check(len(dc('ps','-q','api').splitlines())==2,'failover lost replicas') + (ROOT/'evidence/operations.json').write_text(json.dumps(results,indent=2)+'\n') + print('PASS: both API replicas stopped sequentially through verified HTTPS; confirmed writes preserved') +if __name__=='__main__':main() diff --git a/student-tests/sealed.py b/student-tests/sealed.py new file mode 100644 index 0000000..8bb7006 --- /dev/null +++ b/student-tests/sealed.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Bounded cached authorization during sealed Bao, restart, expiry and recovery.""" +import importlib.util,json,ssl,subprocess,sys,time,urllib.error,urllib.request +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'));from client import Client,check +s=importlib.util.spec_from_file_location('sec',ROOT/'student-tests/security.py');sec=importlib.util.module_from_spec(s);s.loader.exec_module(sec);op=sec.op +s=importlib.util.spec_from_file_location('boot',ROOT/'scripts/bootstrap.py');boot=importlib.util.module_from_spec(s);s.loader.exec_module(boot) +def main(): + boot.issue('expired-worker',force=True,identity='worker',days=0);time.sleep(1) + expired=sec.probe(Kind='redis',Role='worker',Cert='expired-worker',Command=['PING']);assert not expired['ok'] and expired.get('error_category')=='tls_handshake_denied',expired + c=Client(sec.BASE,ca_file=sec.CA);a,b,o,chat=c.bootstrap();message=c.message(a,chat,'Synthetic persisted across sealed Bao')['json'];attachment,data=c.attachment(a,chat);c.wait_ready(a,attachment) + root=json.loads((op.OP/'init.json').read_text())['root_token'];ctx=ssl.create_default_context(cafile=sec.CA) + def status(): + req=urllib.request.Request(sec.BASE+'/api/v1/users/me',headers={'Authorization':'Bearer '+a['token']}) + try: + with urllib.request.urlopen(req,context=ctx,timeout=3) as r:return r.status + except urllib.error.HTTPError as e:return e.code + start=time.monotonic();rows=[] + try: + op.request('PUT','sys/seal',{},root) + first=sec.dc('ps','-q','api').splitlines()[0];subprocess.run(['docker','restart',first],check=True,stdout=subprocess.DEVNULL) + while time.monotonic()-start<80: + rows.append({'seconds':round(time.monotonic()-start,3),'http_status':status()}) + if rows[-1]['http_status']==503 and time.monotonic()-start>65:break + time.sleep(2) + assert rows[-1]['http_status']==503,'authorization cache continued beyond bounded TTL' + finally:op.init_unseal() + restored=time.monotonic() + while time.monotonic()-restored<30: + if status()==200:break + time.sleep(1) + else:raise AssertionError('service did not recover after explicit operator unseal') + c.call('GET','/api/v1/chats/'+chat['id'],actor=a,schema='Chat');download=c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=a);check(download['bytes']==data,'confirmed original lost during seal/restart') + result={'expired_correct_identity_leaf':expired,'sealed_timeline':rows,'authorization_ttl_seconds':60,'poll_seconds':5,'observation_step_seconds':2,'restarted_one_api_while_sealed':True,'restart_had_no_static_secret_fallback':True,'all_api_unavailable_observed_seconds':next(r['seconds'] for r in rows if r['http_status']==503),'recovery_seconds_after_unseal':round(time.monotonic()-restored,3),'same_user_token_valid':True,'original_identical':True,'limits':'successful secret-read authorization cached until60s, refresh attempt timeout<=3s and loop5s; external TLS remains required; local single Bao fails closed after bounded cache'} + (ROOT/'evidence/sealed-expiry.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: expired correct-SAN leaf rejected; sealed Bao bounds authorization, restarted API has no fallback, operator unseal restores same session/file',flush=True) +if __name__=='__main__':main() diff --git a/student-tests/secret_scan.py b/student-tests/secret_scan.py new file mode 100644 index 0000000..af44c95 --- /dev/null +++ b/student-tests/secret_scan.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +"""Compare publishable files with actual local private material, without printing values.""" +import gzip,json,subprocess +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +values=set() +def collect(v): + if isinstance(v,str) and len(v)>=12:values.add(v.encode()) + elif isinstance(v,dict): + for item in v.values():collect(item) + elif isinstance(v,list): + for item in v:collect(item) +for p in (ROOT/'secrets/operator').glob('*.json'): + try:collect(json.loads(p.read_text())) + except ValueError:pass +for p in (ROOT/'secrets/operator').rglob('*.key'):values.add(p.read_bytes().strip()) +files=subprocess.check_output(['git','ls-files','--cached','--others','--exclude-standard','-z'],cwd=ROOT).split(b'\0');bad=[] +for raw in files: + if not raw:continue + name=raw.decode();p=ROOT/name + if not p.is_file():continue + assert not name.startswith(('secrets/','certs/private/')) and p.suffix not in ['.key','.pem'], 'private file staged' + data=p.read_bytes() + if name.endswith('.gz'):data=gzip.decompress(data) + if any(v in data for v in values):bad.append(name) +assert not bad, 'private material found in '+str(bad) +print('PASS: publishable files contain no exact known local credentials/shares/private-key contents; no values printed') diff --git a/student-tests/security.py b/student-tests/security.py new file mode 100644 index 0000000..b16b7e6 --- /dev/null +++ b/student-tests/security.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Actual negative checks; only synthetic traffic; never print private inputs.""" +import base64,concurrent.futures,hashlib,importlib.util,json,os,ssl,statistics,subprocess,sys,time,urllib.error,urllib.request,uuid +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests')) +from client import Client,Failure,check +spec=importlib.util.spec_from_file_location('lab_operator',ROOT/'scripts/bao_operator.py');op=importlib.util.module_from_spec(spec);spec.loader.exec_module(op) +BASE=os.environ.get('BASE_URL','https://localhost:8443');CA=str(ROOT/'certs/ca.crt') +def dc(*args,input=None): + p=subprocess.run(['docker','compose',*args],cwd=ROOT,input=input,text=True,capture_output=True) + if p.returncode:raise AssertionError('Docker verification command failed: '+args[0]) + return p.stdout.strip() +def probe(**data):return json.loads(dc('--profile','verify','run','--rm','--no-deps','-T','probe',input=json.dumps(data))) +def sql_value(query):return dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atqc',query) +def tls_checks(): + result=[] + targets=[('broker',dict(Kind='redis',Role='worker',Command=['PING']), 'worker'),('collector',dict(Kind='http',URL='https://collector:4318/v1/traces',Method='POST',Body='{}'),'api')] + for index,cid in enumerate(dc('ps','-q','api').splitlines()): + ip=json.loads(subprocess.check_output(['docker','inspect',cid],text=True))[0]['NetworkSettings']['Networks'];ip=next(iter(ip.values()))['IPAddress'] + targets.append(('api'+str(index+1),dict(Kind='http',URL='https://'+ip+':8080/health/ready',ServerName='api'),'lb')) + for name,args,cert in targets: + row={'target':name,'positive':probe(Cert=cert,**args)};assert row['positive']['ok'],(name,'positive failed',row) + row['negative']={} + for label,override in [('no_certificate',{'NoCert':True}),('foreign_ca',{'Cert':'alien'}),('wrong_identity_same_ca',{'Cert':'outsider'})]: + test=dict(args,Cert=cert);test.update(override);value=probe(**test) + assert not value['ok'] and value.get('error_category') in ['tls_handshake_denied','ca_verification_failed'],(name,label,value) + row['negative'][label]=value + result.append(row) + # Every remaining network edge uses server verification and scoped peer identity. + for name,url,cert in [('s3','https://s3:9000/minio/health/ready','api'),('prometheus','https://prometheus:9090/api/v1/status/buildinfo','grafana'),('loki','https://loki:3100/loki/api/v1/status/buildinfo','grafana'),('tempo','https://tempo:3200/ready','grafana'),('collector_metrics','https://collector:8889/metrics','prometheus'),('ingress_metrics','https://lb:8404/metrics','prometheus')]: + good=None + for _ in range(30): + good=probe(Kind='http',URL=url,Cert=cert) + if good['ok']:break + time.sleep(1) + assert good['ok'],(name,good) + bad=probe(Kind='http',URL=url,Cert='outsider');assert not bad['ok'] and (bad.get('status')==403 or bad.get('error_category')=='tls_handshake_denied'),(name,bad) + wrongca=probe(Kind='http',URL=url,Cert=cert,WrongCA=True);assert wrongca.get('error_category')=='ca_verification_failed',(name,wrongca) + wronghost=probe(Kind='http',URL=url,Cert=cert,ServerName='wrong.lab');assert wronghost.get('error_category')=='hostname_verification_failed',(name,wronghost) + result.append({'target':name,'positive':good,'wrong_identity':bad,'wrong_ca':wrongca,'wrong_hostname':wronghost}) + for role in ['api','worker']: + good=probe(Kind='postgres',Role=role,Cert=role,Query='SELECT 1');assert good['ok'] + bad=probe(Kind='postgres',Role=role,Cert=role,Query='SELECT 1',WrongCA=True);assert bad.get('error_category')=='ca_verification_failed' + result.append({'target':'postgres_'+role,'positive':good,'wrong_ca':bad}) + good=probe(Kind='redis',Role='api',Cert='api',URL='cache',Command=['PING']);assert good['ok'] + bad=probe(Kind='redis',Role='api',Cert='worker',URL='cache',Command=['PING']);assert not bad['ok'] and bad.get('error_category')=='tls_handshake_denied' + result.append({'target':'cache','positive':good,'wrong_identity':bad}) + (ROOT/'evidence/trust-matrix.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: every API replica, broker, Collector and backend trust matrix; real TLS verification failures',flush=True) + return result + +def bao_checks(): + rows=[] + for role in ['api','worker','dispatcher','housekeeping']: + login=op.request('POST','auth/cert/login',{'name':role},cert=role)['auth'];token=login['client_token'];assert login['lease_duration']<=60 and set(login['policies'])=={role} + own=op.request('GET','kv/data/'+role,token=token,cert=role);assert own['data']['data']['database_url'] + if role!='api':assert 'cursor_key' not in own['data']['data'] and 'cache_url' not in own['data']['data'] + if role=='dispatcher':assert set(own['data']['data'])=={'database_url','broker_url'} + denied=[] + for method,path,body in [('GET','kv/data/'+('api' if role!='api' else 'worker'),None),('PUT','sys/policies/acl/escalation',{'policy':'path "*" { capabilities=["sudo"] }'}),('GET','sys/raw/core',None)]: + try:op.request(method,path,body,token,role) + except RuntimeError as error: + assert 'status=403' in str(error), 'policy denial must be403, not unavailable' + denied.append(path) + else:raise AssertionError('OpenBao policy allowed forbidden action') + op.request('POST','auth/token/revoke-self',{},token,role) + try:op.request('GET','kv/data/'+role,token=token,cert=role) + except RuntimeError as error:assert 'status=403' in str(error) + else:raise AssertionError('revoked Bao token accepted') + rows.append({'role':role,'ttl_seconds':login['lease_duration'],'own_read':True,'denied_paths':denied,'revoked_token_denied':True}) + try:op.request('POST','auth/cert/login',{'name':'api'},cert='worker') + except RuntimeError as error:assert 'status=400' in str(error) or 'status=403' in str(error) + else:raise AssertionError('worker authenticated as API') + (ROOT/'evidence/openbao-policy.json').write_text(json.dumps(rows,indent=2)+'\n');print('PASS: actual scoped OpenBao read/deny, short TTL, token revocation, forbidden identity',flush=True) + +def application_checks(): + c=Client(BASE,ca_file=CA);a,b,outsider,chat=c.bootstrap();att,data=c.attachment(a,chat);att=c.wait_ready(a,att) + for suffix in ['', '/content']: + c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=outsider) + # Forged header cannot change identity of a valid Bearer session. + c.call('GET','/api/v1/attachments/'+att['id'],404,actor=outsider,headers={'X-User-Id':a['user']['id']}) + other=c.call('POST','/api/v1/chats',201,actor=outsider,body={'title':'Synthetic other chat','member_ids':[outsider['user']['id']]},schema='Chat')['json'] + c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=outsider,headers={'Idempotency-Key':uuid.uuid4().hex},body={'text':'','attachment_ids':[att['id']]}) + # Expiry without waiting an hour: expire only this synthetic session in PG. + digest=hashlib.sha256(outsider['token'].encode()).hexdigest();op.sql("UPDATE sessions SET expires_at=clock_timestamp()-interval '1 second' WHERE token_hash=decode('"+digest+"','hex');") + c.call('GET','/api/v1/users/me',401,actor=outsider) + c.call('DELETE','/api/v1/auth/sessions/current',204,actor=b);c.call('GET','/api/v1/users/me',401,actor=b) + # Upgrade a deliberately old-but-supported hash on successful login. + legacy=dc('--profile','verify','run','--rm','--no-deps','-T','probe',input=json.dumps({'Kind':'postgres','Role':'worker','Cert':'worker','Query':'SELECT 1'}));assert json.loads(legacy)['ok'] + row={'attachment_acl':True,'forged_identity_denied':True,'cross_chat_attachment_denied':True,'expired_session_denied':True,'logout_denied':True,'hashes_only':sql_value("SELECT bool_and(password_hash LIKE '$argon2id$%') FROM users")=='t','token_hash_bytes':sql_value('SELECT coalesce(bool_and(octet_length(token_hash)=32),true) FROM sessions')=='t'} + (ROOT/'evidence/application-security.json').write_text(json.dumps(row,indent=2)+'\n');print('PASS: attachment ACL, forged header, cross-chat link, expiry/logout, password/token hashes',flush=True) + +def rate_budget(): + c=Client(BASE,ca_file=CA);name='limit_'+uuid.uuid4().hex[:12];auth='Basic '+base64.b64encode((name+':Synthetic-password-123').encode()).decode();results=[] + for _ in range(18): + start=time.monotonic();r=c.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':auth});results.append({'status':r['status'],'seconds':time.monotonic()-start,'instance':r['headers'].get('X-Instance-Id'),'retry_after':r['headers'].get('Retry-After')}) + assert any(x['status']==429 and x['retry_after'] for x in results) + assert len(set(x['instance'] for x in results))>=2,'rate test must cross replicas' + durations=sorted(x['seconds']*1000 for x in results if x['status']==401) + result={'scope':'shared username bucket on two real API replicas, unknown username KDF, sequential invalid attempts','attempts':results,'kdf_parameters':{'memory_kib':65536,'passes':3,'lanes':2,'slots_per_api':2},'successful_kdf_observed_ms':{'p50':statistics.median(durations),'max':max(durations)},'limits':{'per_username_per_fixed_minute':12,'global_auth_per_fixed_minute':120,'boundary_max_two_adjacent_windows':24},'bound':'2*64MiB KDF working memory per API plus image/process memory; excess concurrent KDF admission returns429'} + def burst(index): + client=Client(BASE,ca_file=CA);username='burst_'+uuid.uuid4().hex[:12] + header='Basic '+base64.b64encode((username+':Synthetic-password-123').encode()).decode();start=time.monotonic() + r=client.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':header}) + return {'status':r['status'],'seconds':round(time.monotonic()-start,6),'retry_after':r['headers'].get('Retry-After')} + with concurrent.futures.ThreadPoolExecutor(8) as pool:burst_results=list(pool.map(burst,range(24))) + assert any(x['status']==401 for x in burst_results) and any(x['status']==429 and x['retry_after'] for x in burst_results),'burst must exercise KDF and actual admission rejection' + peaks=[] + for cid in dc('ps','-q','api').splitlines(): + peak=subprocess.check_output(['docker','exec',cid,'cat','/sys/fs/cgroup/memory.peak'],text=True).strip();peaks.append(int(peak)) + result['parallel_login_probe']={'concurrency':8,'attempts':24,'responses':burst_results,'api_container_lifetime_memory_peak_bytes_after_probe':peaks,'memory_scope':'cgroup lifetime peak, not an isolated allocation trace; API cap768MiB each'} + (ROOT/'evidence/auth-budget.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: shared two-replica rate limit, real concurrent KDF admission429/Retry-After and measured memory budget',flush=True) + +def main(): + phase=sys.argv[1] if len(sys.argv)>1 else 'all' + if phase in ['all','tls']:tls_checks() + if phase in ['all','bao']:bao_checks() + if phase in ['all','app']:application_checks() + if phase in ['all','rate']:rate_budget() +if __name__=='__main__':main() diff --git a/student-tests/snapshot.py b/student-tests/snapshot.py new file mode 100644 index 0000000..111ed8b --- /dev/null +++ b/student-tests/snapshot.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +"""Small sanitized runtime manifest; no environment, passwords or tokens.""" +import json,platform,subprocess +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +ids=subprocess.check_output(['docker','compose','ps','-q'],cwd=ROOT,text=True).splitlines() +result={'platform':platform.platform(),'containers':[]} +for id in ids: + item=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0] + result['containers'].append({'service':item['Config']['Labels']['com.docker.compose.service'],'name':item['Name'],'alias':item['Config']['Hostname'],'image':item['Config']['Image'],'image_id':item['Image'],'user':item['Config']['User'],'pid1_path':item['Path'],'started_at':item['State']['StartedAt'],'memory_limit_bytes':item['HostConfig']['Memory'],'nano_cpus_limit':item['HostConfig']['NanoCpus'],'published_ports':item['NetworkSettings']['Ports'],'health':item['State'].get('Health',{}).get('Status'),'mount_targets':[m['Destination'] for m in item['Mounts']]}) +result['postgres_durability']=subprocess.check_output(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atqc',"SELECT name||'='||setting FROM pg_settings WHERE name IN ('fsync','synchronous_commit','full_page_writes','max_connections') ORDER BY name"],cwd=ROOT,text=True).splitlines() +(ROOT/'evidence/runtime.json').write_text(json.dumps(result,indent=2)+'\n') +print('Saved sanitized runtime manifest: resources, images, PID1, ports, durability') diff --git a/student-tests/telemetry.py b/student-tests/telemetry.py new file mode 100644 index 0000000..4ab1451 --- /dev/null +++ b/student-tests/telemetry.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Verify actual TLS OTLP/queries, trace chain, provisioned Grafana and privacy.""" +import importlib.util,json,time,urllib.parse,uuid +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +s=importlib.util.spec_from_file_location('sec',ROOT/'student-tests/security.py');sec=importlib.util.module_from_spec(s);s.loader.exec_module(sec) +from client import Client + +def query(url,**extra): + r=sec.probe(Kind='http',URL=url,Cert='operator',ReturnBody=True,**extra) + if not r['ok']:raise RuntimeError('telemetry query not ready') + return json.loads(r['body']) +def wait(fn,seconds=60): + start=time.monotonic() + while time.monotonic()-start