forked from mtusi2026/mtusi2026lab7
lab 7 done
This commit is contained in:
@@ -18,3 +18,5 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
|
||||
.runtime
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
## Лабораторная 7
|
||||
|
||||
Автор / группа: TODO
|
||||
Целевая оценка (3/4/5): TODO
|
||||
Трек 5, если заявлен: TODO
|
||||
- Автор и группа — заполняются перед сдачей.
|
||||
- Целевая оценка — **5**.
|
||||
- Трек 1 — компрометация worker.
|
||||
|
||||
Что реализовано и что перенесено: TODO
|
||||
Команды запуска из чистого clone: TODO
|
||||
Результаты проверок и ссылка на REPORT.md: TODO
|
||||
Ограничения / известные ошибки: TODO
|
||||
Источники и использование ИИ: TODO
|
||||
Перенесён мессенджер из lab6. Добавлены HTTPS, mTLS, ограниченные роли, OpenBao и ротация сертификата и секретов worker. [Запуск и результаты](../REPORT.md)
|
||||
|
||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [ ] Контракт и публичные тесты не ослаблены.
|
||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
- [x] Сохранены обязательные возможности мессенджера и публичные проверки.
|
||||
- [x] Настроены модель угроз и матрица доверия.
|
||||
- [x] Проверены HTTPS, mTLS, ACL и политики OpenBao.
|
||||
- [x] Проверена сохранность данных при перезапуске и отказе реплики.
|
||||
- [x] Настроены проверки отзыва worker и восстановления очереди.
|
||||
- [x] Секреты создаются локально. В отчёте приведены обезличенные результаты.
|
||||
|
||||
@@ -30,3 +30,5 @@ coverage/
|
||||
.vscode/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
|
||||
.runtime/
|
||||
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
FROM golang:1.27.3-alpine3.23@sha256:5d5113301ffcac84e2bfb20c42648803fecaea6789c89bb9b66884e18cbb30a7 AS goose-builder
|
||||
RUN GOMAXPROCS=2 GOFLAGS=-p=1 GOBIN=/out CGO_ENABLED=0 go install \
|
||||
-tags='no_clickhouse no_libsql no_mssql no_mysql no_sqlite3 no_vertica no_ydb no_spanner' \
|
||||
github.com/pressly/goose/v3/cmd/goose@v3.27.1
|
||||
|
||||
FROM alpine:3.23@sha256:469c9ea410b9215eaee7976ba6c0639039b444be8e5d638f7abbada189971eb2 AS migrations
|
||||
COPY --from=goose-builder /out/goose /usr/local/bin/goose
|
||||
COPY migrations /migrations
|
||||
COPY infra/migrate.sh /usr/local/bin/migrate
|
||||
USER 10001:10001
|
||||
ENTRYPOINT ["/usr/local/bin/migrate"]
|
||||
CMD ["up"]
|
||||
|
||||
FROM golang:1.27.3-alpine3.23@sha256:5d5113301ffcac84e2bfb20c42648803fecaea6789c89bb9b66884e18cbb30a7 AS builder
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
RUN apk add --no-cache gcc musl-dev
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY cmd ./cmd
|
||||
COPY contracts ./contracts
|
||||
COPY dto ./dto
|
||||
COPY internal ./internal
|
||||
COPY migrations ./migrations
|
||||
ENV GOFLAGS=-p=1 GOMAXPROCS=1 GOMEMLIMIT=192MiB
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build \
|
||||
-trimpath \
|
||||
-ldflags="-s -w" \
|
||||
-o /out/messenger ./cmd
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/reconcile ./cmd/reconcile
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/worker ./cmd/worker
|
||||
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/tlsproxy ./cmd/tlsproxy
|
||||
|
||||
FROM builder AS tests
|
||||
COPY --from=goose-builder /out/goose /usr/local/bin/goose
|
||||
ENV GOOSE_MIGRATION_DIR=/src/migrations
|
||||
CMD ["go", "test", "-p=1", "-race", "-count=1", "-v", "./..."]
|
||||
|
||||
FROM alpine:3.23@sha256:469c9ea410b9215eaee7976ba6c0639039b444be8e5d638f7abbada189971eb2
|
||||
|
||||
RUN apk add --no-cache libwebp-tools=1.6.0-r0
|
||||
|
||||
RUN addgroup -S messenger \
|
||||
&& adduser -S -D -H -u 10001 -G messenger messenger
|
||||
|
||||
COPY --from=builder --chown=messenger:messenger /out/messenger /usr/local/bin/messenger
|
||||
|
||||
COPY --from=builder --chown=messenger:messenger /out/reconcile /usr/local/bin/reconcile
|
||||
|
||||
COPY --from=builder --chown=messenger:messenger /out/worker /usr/local/bin/worker
|
||||
|
||||
COPY --from=builder /out/tlsproxy /usr/local/bin/tlsproxy
|
||||
|
||||
ENV PORT=8080
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
USER messenger:messenger
|
||||
|
||||
STOPSIGNAL SIGTERM
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/messenger"]
|
||||
@@ -0,0 +1,34 @@
|
||||
FROM golang:1.27.3-alpine3.23@sha256:5d5113301ffcac84e2bfb20c42648803fecaea6789c89bb9b66884e18cbb30a7 AS minio-builder
|
||||
ADD --checksum=sha256:8b11129f6a6830768bcdebab569290ad956618f5ff6ef4857b633acb64f95126 https://codeload.github.com/minio/minio/tar.gz/01ce918d8279a20e4706b96a64396146894adee4 /tmp/source.tar.gz
|
||||
RUN mkdir /src && tar -xzf /tmp/source.tar.gz -C /src --strip-components=1
|
||||
WORKDIR /src
|
||||
RUN GOMAXPROCS=1 GOFLAGS=-p=1 GOMEMLIMIT=320MiB CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/minio .
|
||||
RUN echo '8b11129f6a6830768bcdebab569290ad956618f5ff6ef4857b633acb64f95126 /tmp/source.tar.gz' | sha256sum -c -
|
||||
|
||||
FROM alpine:3.23@sha256:469c9ea410b9215eaee7976ba6c0639039b444be8e5d638f7abbada189971eb2 AS minio
|
||||
LABEL org.opencontainers.image.source="https://github.com/minio/minio" \
|
||||
org.opencontainers.image.revision="01ce918d8279a20e4706b96a64396146894adee4" \
|
||||
org.opencontainers.image.version="RELEASE.2025-09-07T16-13-09Z" \
|
||||
org.opencontainers.image.licenses="AGPL-3.0"
|
||||
RUN mkdir /data && chown 10001:10001 /data
|
||||
COPY --from=minio-builder /out/minio /usr/local/bin/minio
|
||||
COPY infra/minio-entrypoint.sh /usr/local/bin/start-minio
|
||||
USER 10001:10001
|
||||
EXPOSE 9000
|
||||
ENTRYPOINT ["/usr/local/bin/start-minio"]
|
||||
|
||||
FROM golang:1.27.3-alpine3.23@sha256:5d5113301ffcac84e2bfb20c42648803fecaea6789c89bb9b66884e18cbb30a7 AS mc-builder
|
||||
ADD --checksum=sha256:4cea8ed209c8f96e59ea1a5cc4901019b54c2be6d6f5f16c6749ea8bdcf4172e https://codeload.github.com/minio/mc/tar.gz/d6541ea280b73a834b64d4097e21f2be77676104 /tmp/source.tar.gz
|
||||
RUN mkdir /src && tar -xzf /tmp/source.tar.gz -C /src --strip-components=1
|
||||
WORKDIR /src
|
||||
RUN GOMAXPROCS=1 GOFLAGS=-p=1 GOMEMLIMIT=320MiB CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/mc .
|
||||
RUN echo '4cea8ed209c8f96e59ea1a5cc4901019b54c2be6d6f5f16c6749ea8bdcf4172e /tmp/source.tar.gz' | sha256sum -c -
|
||||
|
||||
FROM alpine:3.23@sha256:469c9ea410b9215eaee7976ba6c0639039b444be8e5d638f7abbada189971eb2 AS mc
|
||||
LABEL org.opencontainers.image.source="https://github.com/minio/mc" \
|
||||
org.opencontainers.image.revision="d6541ea280b73a834b64d4097e21f2be77676104" \
|
||||
org.opencontainers.image.version="RELEASE.2025-08-13T08-35-41Z" \
|
||||
org.opencontainers.image.licenses="AGPL-3.0"
|
||||
COPY --from=mc-builder /out/mc /usr/local/bin/mc
|
||||
USER 10001:10001
|
||||
ENTRYPOINT ["mc"]
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
Защитить работающий мессенджер на границах доверия и показать защиту отрицательными проверками: чужой доступ, неверный сертификат, недостаточные права и отзыв credentials.
|
||||
|
||||
Это **skeleton**, а не готовый сервер. Здесь есть задание, контракт и публичные проверки. Реализацию приложения, Dockerfile и требуемую инфраструктуру пишет студент. Язык и framework свободные; UI не обязателен.
|
||||
В этой ветке есть решение на Go и стенд Docker Compose. Цель — оценка «5», трек «Компрометация worker». [Запуск, проверки и результаты](REPORT.md).
|
||||
|
||||
Исходное задание, контракт и публичные проверки приведены ниже.
|
||||
|
||||
[Карта курса](COURSE.md) · [Процесс fork/PR](CONTRIBUTING.md) · [OpenAPI](contracts/openapi.json) · [Семантика API](contracts/README.md) · [Проверки](tests/README.md) · [Отчёт](REPORT.md) · [Примеры JSON](contracts/examples.json) · [Памятка преподавателю](MAINTAINERS.md)
|
||||
|
||||
|
||||
@@ -1,37 +1,167 @@
|
||||
# Отчёт — лабораторная 7
|
||||
# Отчёт по лабораторной №7
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Целевая оценка — **5**.
|
||||
- Трек 1 — компрометация worker.
|
||||
- Автор и группа — заполняются перед сдачей.
|
||||
- Источник переноса — `mtusi2026lab6`, коммит `4ab9b0e`.
|
||||
- Средства — Go, Echo, PostgreSQL, Redis Streams, MinIO, OpenTelemetry, OpenBao, Docker Compose, Trivy. Для переноса, реализации и проверки использован Codex.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Установите Docker Engine с Compose v2 или совместимым `docker-compose`. Установите Python 3.9+, OpenSSL и Make. Оставьте порты 8443, 13000 и 18200 свободными на loopback. Для сборки выделите Docker не менее 2 GiB памяти. Первый запуск скачивает образы и зависимости. Docker собирает MinIO и mc из архивов исходного кода.
|
||||
|
||||
## Архитектура и решения
|
||||
```sh
|
||||
python3 scripts/stand.py bootstrap
|
||||
python3 scripts/wait_ready.py
|
||||
make check
|
||||
make test CA_FILE=.runtime/trust/ca.crt
|
||||
make test-security CA_FILE=.runtime/trust/ca.crt
|
||||
```
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Bootstrap создаёт локальный CA, сертификаты и секреты. Затем он собирает образы и запускает хранилища. OpenBao сохраняет данные в томе `openbao_data`. Bootstrap выполняет init/unseal, сохраняет политики и настраивает роли. Goose применяет 11 миграций из lab6 по TLS. Команды оператора задают права PostgreSQL и MinIO. Затем запускаются две реплики API, worker и подсистема телеметрии.
|
||||
|
||||
## Доказательства критериев
|
||||
На контрольной сборке загрузка двух модулей для `mc` завершилась сетевым EOF. Повторная сборка использовала кэш модулей и проверила SHA-256 исходного архива. Собранная утилита прошла настройку бакета и проверку прав S3. [Проверка mc](evidence/mc-verification.txt)
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
Если образы уже собраны, передайте `--skip-build`. Для обычного запуска после остановки выполните команды ниже.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
```sh
|
||||
./scripts/compose.sh up -d --no-build
|
||||
python3 scripts/stand.py unseal
|
||||
python3 scripts/wait_ready.py
|
||||
```
|
||||
|
||||
## Эксперименты и отказы
|
||||
Откройте Grafana по адресу `https://localhost:13000`. Используйте логин `admin` и пароль из файла `.runtime/bootstrap/grafana/GRAFANA_PASSWORD`. Доверяйте CA стенда в клиенте. Приватный ключ CA, корневой токен и доли Shamir хранятся в каталоге `.runtime/operator` с доступом только оператора. Compose не монтирует этот каталог в контейнеры.
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Для остановки с сохранением томов выполните `./scripts/compose.sh stop`. Для намеренного сброса учебных данных выполните `./scripts/compose.sh down -v`. Перед новым bootstrap после сброса перенесите `.runtime` в закрытый архив. Старые доли Shamir относятся к удалённому тому OpenBao.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
## Архитектура
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
```text
|
||||
клиент ─TLS─> HAProxy ─mTLS─> API × 2
|
||||
│
|
||||
API / worker ─TLS───────────── PostgreSQL, MinIO, OpenBao
|
||||
API / worker ─mTLS──────────── Redis Streams и сессии, Collector
|
||||
Collector ─mTLS─────────────── Tempo, Loki
|
||||
Prometheus ─mTLS────────────── Collector, Tempo, Loki
|
||||
Grafana ─mTLS───────────────── Prometheus, Tempo, Loki
|
||||
```
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Из lab6 перенесены HTTP-обработчики, история, курсоры, сессии, идемпотентность, вложения и телеметрия. PostgreSQL хранит согласованное состояние задач, метаданных и transactional outbox. Redis Streams доставляет события как минимум один раз. Worker берёт задачу по lease, фиксирует результат и подтверждает сообщение после записи состояния. MinIO хранит исходные файлы и производные изображения.
|
||||
|
||||
Go-приложения получают настройки из Compose, а рабочие ключи из OpenBao. Оператор задаёт имена ролей и адреса зависимостей в `compose.yaml`. Можно переопределить `PORT` и `SESSION_TTL_SECONDS` через окружение запуска `scripts/compose.sh`. Go 1.27.3 и Alpine закреплены digest. Версии остальных образов указаны в Compose. [Матрица доверия](contracts/trust-matrix.md) · [Модель угроз](security/THREAT_MODEL.md)
|
||||
|
||||
## Проверки уровня 3 и 4
|
||||
|
||||
Для работы с сертификатами используйте CA стенда во всех командах. Команды `audit` запускает оператор.
|
||||
|
||||
```sh
|
||||
./scripts/compose.sh run --rm --no-deps audit matrix
|
||||
./scripts/compose.sh run --rm --no-deps audit bao-expiry
|
||||
python3 security/http_checks.py authorization
|
||||
python3 security/http_checks.py rate
|
||||
python3 security/http_checks.py telemetry
|
||||
go test -run '^$' -bench BenchmarkVerify -benchtime=1s -count=3 ./internal/pkg/password
|
||||
python3 security/hardening.py
|
||||
python3 security/seal_experiment.py
|
||||
```
|
||||
|
||||
Для проверки короткой сессии временно пересоздайте API. Для остальных проверок оставьте штатный TTL 3600 секунд.
|
||||
|
||||
```sh
|
||||
SESSION_TTL_SECONDS=8 ./scripts/compose.sh up -d --no-build --no-deps api
|
||||
python3 scripts/wait_ready.py
|
||||
python3 security/http_checks.py expiry
|
||||
./scripts/compose.sh up -d --no-build --no-deps api
|
||||
python3 scripts/wait_ready.py
|
||||
```
|
||||
|
||||
Перед проверкой отказа дождитесь обеих API-реплик. После каждого отказа восстановите реплику через Compose.
|
||||
|
||||
```sh
|
||||
make test-persistence CA_FILE=.runtime/trust/ca.crt ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover CA_FILE=.runtime/trust/ca.crt ACTION_SCRIPT=scripts/stop-one.sh
|
||||
./scripts/compose.sh up -d --no-build api
|
||||
make test-failover CA_FILE=.runtime/trust/ca.crt ACTION_SCRIPT=scripts/stop-one.sh
|
||||
./scripts/compose.sh up -d --no-build api
|
||||
```
|
||||
|
||||
| Критерий | Наблюдение и доказательство |
|
||||
| --- | --- |
|
||||
| Публичный API через HTTPS | Smoke проверяет пользователей, историю, идемпотентность, вложения, thumbnail и logout. [Вывод](evidence/smoke.txt) |
|
||||
| Недоверенный TLS, mTLS и SAN | Клиент отклоняет плохой CA и имя. Обе API-реплики отклоняют пустой сертификат, чужой CA и постороннюю роль. [Матрица](evidence/tls-audit.txt) |
|
||||
| Остальные TLS-связи | Пробы проверяют роли Redis и Collector, пути телеметрии и отсутствие сетевого доступа к loopback-портам. [Матрица](evidence/tls-audit.txt) |
|
||||
| Пароли и сессии | Argon2id хранит соль и параметры. Неактуальный bcrypt или Argon2id обновляется после успешного входа. PostgreSQL применяет сравнение с прежним хэшем. Redis хранит SHA-256 токена. [Измерение Argon2id](evidence/argon2.txt) · [HTTP-проверки](evidence/http-security.txt) |
|
||||
| Бюджет дорогостоящего входа | Argon2id использует 19 MiB, два прохода и один поток. Лимит на реплику — четыре KDF одновременно. Лимиты Redis — 8 попыток на имя и 120 на стенд за 30 секунд. Девятая попытка получает 429 и `Retry-After`. [Измерение Argon2id](evidence/argon2.txt) · [HTTP-проверки](evidence/http-security.txt) |
|
||||
| Размер и ACL вложений | Запрос с большим `Content-Length` получает 413. API ограничивает потоковое чтение. Посторонний пользователь не может прочитать вложение или привязать его к своему чату. [HTTP-проверки](evidence/http-security.txt) |
|
||||
| Scoped OpenBao и TTL | cert auth выдаёт токен на 30 секунд. Роль читает свой KV-путь. Чтение другого пути, запись политики и просроченный токен получают 403. [Проверка](evidence/openbao-expiry.txt) · [Инициализация пустого хранилища](evidence/openbao-bootstrap.txt) |
|
||||
| Sealed OpenBao | После допуска на время сбоя API прекращает обслуживание. После unseal прежняя сессия снова работает. [Наблюдение](evidence/seal.json) |
|
||||
| Ограничения контейнеров | Compose задаёт read-only root filesystem, tmpfs, сброс capabilities и no-new-privileges. Worker ограничен CPU, памятью, 25 секундами на обработку и 40 млн пикселей. [Runtime](evidence/hardening.jsonl) |
|
||||
| Телеметрия | Grafana видит трассы, логи и метрики тестовых запросов. Проверка ищет пароль, имя, Basic и Bearer внутри выгрузок в памяти. [HTTP-проверки](evidence/http-security.txt) |
|
||||
| Persistence и отказ API | Скрипт перезапускает хранилища с сохранением томов. При отказе останавливается одна реплика. Тест проверяет прежний токен, записи и SHA-256 вложения. [Persistence](evidence/persistence.txt) · [Том и процессы](evidence/persistence-containers.txt) · [Failover](evidence/failover.txt) · [Остановленные реплики](evidence/failover-containers.txt) |
|
||||
| Ротация сертификата и паролей | Сертификат worker отзывается, даже если его подписал CA стенда. Права Redis, PostgreSQL и S3 переходят на новые учётные данные. [Проход эксперимента](evidence/worker-access.txt) |
|
||||
| Сканирование зависимостей и образов | Trivy проверяет зависимости и слои образов. Разбор соотносит находки с путями стенда. [Разбор](evidence/scan-triage.md) |
|
||||
|
||||
Каталоги данных PostgreSQL, Redis, MinIO, OpenBao и трёх backend телеметрии требуют записи. Именованные тома обеспечивают запись. Grafana хранит SQLite и состояние панели в своём томе. Файлы ключей монтируются по ролям только для чтения. API и worker получают только свой сертификат, ключ и общий открытый набор доверия.
|
||||
|
||||
## Трек 1. Компрометация worker
|
||||
|
||||
**Гипотеза.** Worker может обработать изображения в пределах роли. Роль не даёт доступа к сообщениям, сессиям и чужим путям OpenBao. После отзыва сертификата и ротации учётных данных все принятые задачи дойдут до `ready`.
|
||||
|
||||
Запустите сценарий на учебном стенде. Он меняет действующие учётные данные worker и добавляет синтетические данные.
|
||||
|
||||
```sh
|
||||
python3 security/worker_experiment.py --jobs 8 --repeats 3 --output evidence/worker-experiment.json
|
||||
```
|
||||
|
||||
Сценарий проверяет права worker штатными запросами. Затем он загружает контрольную группу PNG и проверяет результаты. Worker останавливается до второй группы. Через 2 секунды все восемь вложений ещё имеют статус `queued`. Скрипт отзывает старый сертификат на Redis, Collector и OpenBao. Скрипт меняет пароль Redis и пароль роли PostgreSQL. В MinIO скрипт выдаёт новый ключ доступа.
|
||||
|
||||
Перед публикацией новых учётных данных скрипт ждёт 31 секунду. К этому моменту токены старой привязки OpenBao истекают. Скрипт запускает worker из прежнего образа. Он проверяет оригиналы, варианты и историю чата. Старые учётные данные проверяются отдельными TLS-соединениями. [Данные эксперимента](evidence/worker-experiment.json)
|
||||
|
||||
| Ресурс | Права в lab6 по настройкам проекта | Права worker в lab7 |
|
||||
| --- | --- | --- |
|
||||
| PostgreSQL | Пароль владельца базы общий для API и worker. Роль читала пользователей и сообщения. | Worker читает только поля обработки. Он меняет состояние задач и служебные поля вложений. DDL, удаление задач и чтение сообщений запрещены. |
|
||||
| Redis | Общий клиент без пароля. Worker имел доступ к сессиям и любым командам. | Worker читает один stream и подтверждает доставку. Публикация, чужой stream, чтение сессии и административная очистка запрещены. |
|
||||
| MinIO | Общая роль могла читать, писать и удалять объекты двух префиксов. | Worker читает staging и удаляет отработанные объекты. Он пишет в original. Запись в staging, чужой префикс и S3 admin запрещены. |
|
||||
| OpenBao | Рабочие пароли попадали в API и worker через локальные файлы. | Worker получает отдельный KV-путь. Политика ограничивает доступ к секретам API и операциям администратора. |
|
||||
|
||||
Docker работал на Linux/arm64 с двумя vCPU и 1,91 GiB памяти. Worker получил 0,75 vCPU и 384 MiB. Методика использует один файл PNG, четыре параллельные отправки и три повтора. Выборку CPU и памяти worker получают через `docker stats`. p50/p95/p99 рассчитываются методом ближайшего ранга. Время до готовности включает опрос HTTP. throughput считает результаты, которые проверил клиент. Это оценка восстановления малой очереди с синтетическими вложениями. При восьми наблюдениях за повтор p95 и p99 совпадают с максимумом. Контрольные запросы повторяют чтение после временной ошибки и считают повторы.
|
||||
|
||||
### Результаты
|
||||
|
||||
Все 24 принятые в период остановки задачи дошли до `ready`. Исходные файлы и история сохранились. Повторов чтения в итоговых прогонах не было.
|
||||
|
||||
| Повтор | Контроль p95 до ready, с | После остановки p95 до ready, с | От запуска до готовности всей очереди, с | Потери и дубли |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| 1 | 0,93 | 35,04 | 1,22 | 0 |
|
||||
| 2 | 0,97 | 35,44 | 1,33 | 0 |
|
||||
| 3 | 0,99 | 35,24 | 1,26 | 0 |
|
||||
|
||||
Контрольная группа показала 6,67–7,22 проверенных задач в секунду. Ротация длилась 31,62–31,81 секунды. Результат включает ожидание срока жизни токенов и запуск worker. Параллельно шла сборка образа MinIO. Она могла повлиять на измеренное время. Образы зафиксированы для этого прогона. [Идентификаторы образов](evidence/experiment-images.txt)
|
||||
|
||||
Перед итоговым прогоном API получил 503 при обращении к закрытому соединению Redis. Пул теперь заменяет соединение через 60 секунд. Предел прокси составляет 90 секунд. [Результаты эксперимента](evidence/worker-experiment.json)
|
||||
|
||||
На пересобранном MinIO подтвердили ещё восемь задач из восьми. После запуска worker очередь этих задач обработалась за 1,22 секунды. [Замеры](evidence/worker-final-stack.json) · [Права и отзыв](evidence/worker-final-stack-access.txt)
|
||||
|
||||
### Повторная проверка телеметрии
|
||||
|
||||
Во время уплотнения трасс Tempo достиг лимита 320 MiB и остановился. Публичный HTTPS smoke прошёл во время отказа Tempo. После восстановления Tempo Compose задаёт лимит 512 MiB и включает перезапуск. Пакет уплотнения ограничен 20 000 объектов. [Проверка после восстановления](evidence/tempo-recovery.txt)
|
||||
|
||||
### Проверка нового функционала 29 ноября
|
||||
|
||||
Повторили отрицательные проверки mTLS, ограничений OpenBao, доступа к вложениям и лимита входа. Собранный `mc` прошёл проверку прав S3. После ротации worker обработал восемь задач из восьми за 1,19 секунды с момента запуска. [Вывод проверок](evidence/lab7-verification.txt) · [Замеры](evidence/lab7-verification-worker.json)
|
||||
|
||||
## Эксплуатационные ограничения
|
||||
|
||||
Leaf действуют 7 суток. Для плановой замены остановите стенд, выполните `python3 scripts/stand.py renew-leaves` и повторите bootstrap с `--skip-build`. Команда обновит привязки OpenBao и настройки Grafana. Для worker есть отдельная ротация без остановки API.
|
||||
|
||||
Один Docker-хост, HAProxy и хранилища остаются одиночными точками отказа. Отказ worker оставляет задачи в очереди. PostgreSQL и MinIO нужны для приёма новых вложений. Доступ к API завершается при долгом сбое OpenBao. Если пропадёт том, восстановление потребует резервной копии. Эксперимент не моделирует потерю тома или владельца Docker.
|
||||
|
||||
Скомпрометированный worker может менять состояние обработки и портить объекты в `original/`. Границы S3 действуют на префиксы. Они не разделяют объекты отдельных чатов. Тест на утечки покрывает запросы входа и чтения собственного профиля. [Модель угроз](security/THREAT_MODEL.md)
|
||||
|
||||
## Источники
|
||||
|
||||
- [OWASP Password Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html)
|
||||
- [OpenBao cert auth](https://openbao.org/docs/auth/cert/)
|
||||
- [Декларативный аудит OpenBao](https://openbao.org/blog/features-declarative-configuration/)
|
||||
- [Redis ACL](https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/)
|
||||
- [Trivy](https://trivy.dev/)
|
||||
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/observability"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/session"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/trust"
|
||||
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
|
||||
)
|
||||
|
||||
const shutdownTimeout = 8 * time.Second
|
||||
|
||||
func main() {
|
||||
shutdownTelemetry, telemetryErr := observability.Init(context.Background(), "messenger-api")
|
||||
if telemetryErr != nil {
|
||||
log.Fatal("telemetry configuration failed")
|
||||
}
|
||||
defer shutdownTelemetry()
|
||||
cfg, err := config.LoadService()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
poolConfig, err := cfg.PostgresConfig()
|
||||
if err != nil {
|
||||
log.Fatal("invalid PostgreSQL config")
|
||||
}
|
||||
poolConfig.ConnConfig.Host = cfg.PostgresHost
|
||||
poolConfig.ConnConfig.Port = cfg.PostgresPort
|
||||
poolConfig.ConnConfig.User = cfg.PostgresUser
|
||||
poolConfig.ConnConfig.Database = cfg.PostgresDatabase
|
||||
poolConfig.ConnConfig.Password = cfg.PostgresPassword
|
||||
poolConfig.ConnConfig.ConnectTimeout = cfg.QueryTimeout
|
||||
poolConfig.ConnConfig.RuntimeParams["timezone"] = "UTC"
|
||||
poolConfig.ConnConfig.RuntimeParams["statement_timeout"] = fmt.Sprint(cfg.QueryTimeout.Milliseconds())
|
||||
poolConfig.ConnConfig.Tracer = observability.DBTracer{}
|
||||
poolConfig.MaxConns = cfg.PostgresMaxConns
|
||||
poolConfig.MinConns = 1
|
||||
poolConfig.MaxConnLifetime = time.Hour
|
||||
poolConfig.MaxConnIdleTime = 5 * time.Minute
|
||||
pool, err := pgxpool.NewWithConfig(context.Background(), poolConfig)
|
||||
if err != nil {
|
||||
log.Fatal("cannot create PostgreSQL pool")
|
||||
}
|
||||
defer pool.Close()
|
||||
observability.ObservePool(pool, 0)
|
||||
redisOptions, err := cfg.RedisOptions()
|
||||
if err != nil {
|
||||
log.Fatal("invalid Redis TLS configuration")
|
||||
}
|
||||
redisClient := redis.NewClient(redisOptions)
|
||||
defer redisClient.Close()
|
||||
repo := postgres.New(pool, cfg.QueryTimeout)
|
||||
sessions := session.NewRedis(redisClient, cfg.QueryTimeout)
|
||||
useCase := chatusecase.New(repo, sessions, cfg.SessionTTL)
|
||||
objectStore, err := attachment.NewStore(cfg.S3Endpoint, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey, cfg.S3UseSSL)
|
||||
if err != nil {
|
||||
log.Fatal("invalid S3 config")
|
||||
}
|
||||
options, err := attachment.LoadOptions()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
attachments := attachment.NewAsync(pool, objectStore, options)
|
||||
background, stopPublisher := context.WithCancel(context.Background())
|
||||
defer stopPublisher()
|
||||
go attachments.RunPublisher(background, redisClient)
|
||||
handler := chat.NewChat(useCase, cfg.CursorKey).WithAttachments(attachments).WithLoginLimit(sessions.LoginAllowed)
|
||||
port := cfg.Port
|
||||
e := handler.Router()
|
||||
e.Server.ReadHeaderTimeout = 5 * time.Second
|
||||
e.Server.MaxHeaderBytes = 16 << 10
|
||||
e.Server.ReadTimeout = 50 * time.Second
|
||||
e.Server.WriteTimeout = 55 * time.Second
|
||||
e.Server.IdleTimeout = 60 * time.Second
|
||||
|
||||
e.Server.TLSConfig, err = trust.Server("/trust/ca.crt", "/identity/tls.crt", "/identity/tls.key", "gateway", "/trust/revoked")
|
||||
if err != nil {
|
||||
log.Fatal("invalid API TLS configuration")
|
||||
}
|
||||
e.Server.TLSConfig.NextProtos = []string{"http/1.1"}
|
||||
e.Server.Addr = ":" + port
|
||||
serverErrors := make(chan error, 1)
|
||||
go func() {
|
||||
log.Printf("HTTP server is listening on :%s", port)
|
||||
serverErrors <- e.Server.ListenAndServeTLS("", "")
|
||||
}()
|
||||
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
|
||||
select {
|
||||
case sig := <-stop:
|
||||
log.Printf("received %s, shutting down", sig)
|
||||
case err := <-serverErrors:
|
||||
if !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatalf("HTTP server failed: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
handler.Drain()
|
||||
// Allow two 1-second LB checks to remove this backend before closing the listener.
|
||||
time.Sleep(3 * time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
||||
defer cancel()
|
||||
if err := e.Shutdown(ctx); err != nil {
|
||||
log.Printf("graceful shutdown failed: %v", err)
|
||||
if closeErr := e.Close(); closeErr != nil {
|
||||
log.Printf("forced shutdown failed: %v", closeErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Printf("shutdown complete")
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func main() {
|
||||
apply := flag.Bool("apply", false, "apply safe repairs; default dry-run")
|
||||
grace := flag.Duration("grace", 2*time.Minute, "minimum object/metadata age (at least 90s)")
|
||||
timeout := flag.Duration("timeout", 10*time.Minute, "whole scan deadline")
|
||||
flag.Parse()
|
||||
if *grace < attachment.MinimumGrace {
|
||||
log.Fatal("grace must be at least 90s")
|
||||
}
|
||||
cfg, err := config.LoadService()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
pc, err := cfg.PostgresConfig()
|
||||
if err != nil {
|
||||
log.Fatal("invalid DB config")
|
||||
}
|
||||
pc.ConnConfig.Host = cfg.PostgresHost
|
||||
pc.ConnConfig.Port = cfg.PostgresPort
|
||||
pc.ConnConfig.User = cfg.PostgresUser
|
||||
pc.ConnConfig.Password = cfg.PostgresPassword
|
||||
pc.ConnConfig.Database = cfg.PostgresDatabase
|
||||
pc.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
pc.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
|
||||
pc.MaxConns = 2
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
pool, err := pgxpool.NewWithConfig(ctx, pc)
|
||||
if err != nil {
|
||||
log.Fatal("cannot create DB pool")
|
||||
}
|
||||
defer pool.Close()
|
||||
store, err := attachment.NewStore(cfg.S3Endpoint, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey, cfg.S3UseSSL)
|
||||
if err != nil {
|
||||
log.Fatal("invalid S3 config")
|
||||
}
|
||||
result, err := attachment.New(pool, store).Reconcile(ctx, *apply, *grace)
|
||||
_ = json.NewEncoder(os.Stdout).Encode(result)
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// tlsproxy terminates TLS in the backend's network namespace. Targets must be loopback.
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/trust"
|
||||
)
|
||||
|
||||
func main() {
|
||||
for _, route := range strings.Split(os.Getenv("TLS_ROUTES"), ";") {
|
||||
fields := strings.SplitN(route, "=", 4)
|
||||
if len(fields) < 3 {
|
||||
log.Fatal("invalid TLS route")
|
||||
}
|
||||
cfg, err := trust.Server("/trust/ca.crt", "/identity/tls.crt", "/identity/tls.key", fields[2], "/trust/revoked")
|
||||
if err != nil {
|
||||
log.Fatal("TLS configuration failed")
|
||||
}
|
||||
listener, err := tls.Listen("tcp", ":"+fields[0], cfg)
|
||||
if err != nil {
|
||||
log.Fatal("TLS listener failed")
|
||||
}
|
||||
target := "127.0.0.1:" + fields[1]
|
||||
if len(fields) == 4 {
|
||||
go serveHTTP(listener, target, fields[3])
|
||||
} else {
|
||||
go serve(listener, target)
|
||||
}
|
||||
}
|
||||
select {}
|
||||
}
|
||||
|
||||
func serve(listener net.Listener, target string) {
|
||||
slots := make(chan struct{}, 256)
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
log.Fatal("TLS accept failed")
|
||||
}
|
||||
select {
|
||||
case slots <- struct{}{}:
|
||||
go func() {
|
||||
defer func() { <-slots }()
|
||||
tunnel(conn.(*tls.Conn), target)
|
||||
}()
|
||||
default:
|
||||
conn.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func tunnel(client *tls.Conn, target string) {
|
||||
defer client.Close()
|
||||
client.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
if err := client.Handshake(); err != nil {
|
||||
return
|
||||
}
|
||||
// Bound the lifetime of established connections after a leaf has been revoked.
|
||||
deadline := time.Now().Add(90 * time.Second)
|
||||
if leafs := client.ConnectionState().PeerCertificates; len(leafs) > 0 && leafs[0].NotAfter.Before(deadline) {
|
||||
deadline = leafs[0].NotAfter
|
||||
}
|
||||
client.SetDeadline(deadline)
|
||||
backend, err := net.DialTimeout("tcp", target, 2*time.Second)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer backend.Close()
|
||||
backend.SetDeadline(deadline)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
io.Copy(backend, client)
|
||||
backend.(*net.TCPConn).CloseWrite()
|
||||
close(done)
|
||||
}()
|
||||
io.Copy(client, backend)
|
||||
client.Close()
|
||||
<-done
|
||||
}
|
||||
|
||||
func serveHTTP(listener net.Listener, target, rule string) {
|
||||
upstream := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "http", Host: target})
|
||||
upstream.Transport = &http.Transport{
|
||||
DialContext: (&net.Dialer{Timeout: 2 * time.Second}).DialContext,
|
||||
ResponseHeaderTimeout: 10 * time.Second, IdleConnTimeout: 15 * time.Second,
|
||||
}
|
||||
upstream.ErrorHandler = func(w http.ResponseWriter, _ *http.Request, _ error) {
|
||||
http.Error(w, "backend unavailable", http.StatusBadGateway)
|
||||
}
|
||||
allowed := strings.Split(rule, ",")
|
||||
server := &http.Server{
|
||||
ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second, IdleTimeout: 15 * time.Second,
|
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
for _, candidate := range allowed {
|
||||
method, path, _ := strings.Cut(candidate, ":")
|
||||
if r.Method == method && (r.URL.Path == path ||
|
||||
(strings.HasSuffix(path, "/") && strings.HasPrefix(r.URL.Path, path))) {
|
||||
upstream.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.Error(w, "endpoint denied", http.StatusForbidden)
|
||||
}),
|
||||
}
|
||||
if err := server.Serve(listener); err != nil {
|
||||
log.Fatal("TLS HTTP server failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/observability"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) > 1 && os.Args[1] == "render" {
|
||||
if len(os.Args) != 5 {
|
||||
os.Exit(2)
|
||||
}
|
||||
if err := attachment.Render(context.Background(), os.Args[2], os.Args[3], os.Args[4]); err != nil {
|
||||
if errors.Is(err, attachment.ErrInvalidImage) {
|
||||
os.Exit(2)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
failed := flag.Bool("failed", false, "list failed job registry")
|
||||
replay := flag.String("replay", "", "failed job UUID to replay")
|
||||
operator := flag.String("operator", "", "operator identity")
|
||||
reason := flag.String("reason", "", "replay reason")
|
||||
flag.Parse()
|
||||
shutdownTelemetry, telemetryErr := observability.Init(context.Background(), "messenger-worker")
|
||||
if telemetryErr != nil {
|
||||
log.Fatal("telemetry configuration failed")
|
||||
}
|
||||
defer shutdownTelemetry()
|
||||
cfg, err := config.LoadService()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
options, err := attachment.LoadOptions()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
pc, err := cfg.PostgresConfig()
|
||||
if err != nil {
|
||||
log.Fatal("invalid DB config")
|
||||
}
|
||||
pc.ConnConfig.Host = cfg.PostgresHost
|
||||
pc.ConnConfig.Port = cfg.PostgresPort
|
||||
pc.ConnConfig.User = cfg.PostgresUser
|
||||
pc.ConnConfig.Password = cfg.PostgresPassword
|
||||
pc.ConnConfig.Database = cfg.PostgresDatabase
|
||||
pc.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
pc.ConnConfig.RuntimeParams["timezone"] = "UTC"
|
||||
pc.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
|
||||
pc.ConnConfig.Tracer = observability.DBTracer{}
|
||||
pc.MaxConns = int32(options.Concurrency + 4)
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
pool, err := pgxpool.NewWithConfig(ctx, pc)
|
||||
if err != nil {
|
||||
log.Fatal("DB configuration failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
observability.ObservePool(pool, options.Concurrency)
|
||||
store, err := attachment.NewStore(cfg.S3Endpoint, cfg.S3Bucket, cfg.S3AccessKey, cfg.S3SecretKey, cfg.S3UseSSL)
|
||||
if err != nil {
|
||||
log.Fatal("S3 configuration failed")
|
||||
}
|
||||
service := attachment.NewAsync(pool, store, options)
|
||||
if *failed {
|
||||
rows, e := pool.Query(ctx, `SELECT id::text,attachment_id::text,attempts,max_attempts,coalesce(last_error,''),updated_at FROM attachment_jobs WHERE state='failed' ORDER BY updated_at DESC LIMIT 100`)
|
||||
if e != nil {
|
||||
log.Fatal("cannot query failed jobs")
|
||||
}
|
||||
defer rows.Close()
|
||||
records := []map[string]interface{}{}
|
||||
for rows.Next() {
|
||||
var id, att, code string
|
||||
var attempt, max int
|
||||
var updated time.Time
|
||||
if e = rows.Scan(&id, &att, &attempt, &max, &code, &updated); e != nil {
|
||||
log.Fatal("invalid failed job")
|
||||
}
|
||||
records = append(records, map[string]interface{}{"job_id": id, "attachment_id": att, "attempts": attempt, "max_attempts": max, "error_code": code, "updated_at": updated.UTC()})
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
log.Fatal("failed jobs query interrupted")
|
||||
}
|
||||
json.NewEncoder(os.Stdout).Encode(records)
|
||||
return
|
||||
}
|
||||
if *replay != "" {
|
||||
operation, stop := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer stop()
|
||||
if err = service.Replay(operation, *replay, *operator, *reason); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Print("Replay committed with audit record")
|
||||
return
|
||||
}
|
||||
redisOptions, err := cfg.RedisOptions()
|
||||
if err != nil {
|
||||
log.Fatal("invalid Redis TLS configuration")
|
||||
}
|
||||
r := redis.NewClient(redisOptions)
|
||||
defer r.Close()
|
||||
log.Printf("Worker started: concurrency=%d prefetch=%d timeout=%s lease=%s pixel_budget=%d", options.Concurrency, options.Prefetch, options.Timeout, options.Lease, options.PixelBudget)
|
||||
for ctx.Err() == nil {
|
||||
err = service.RunWorker(ctx, r)
|
||||
if err != nil {
|
||||
log.Print("worker broker connection will retry")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
name: mtusi2026lab7
|
||||
|
||||
x-hardening: &hardening
|
||||
read_only: true
|
||||
security_opt: [no-new-privileges:true]
|
||||
cap_drop: [ALL]
|
||||
tmpfs: ['/tmp:size=64m,mode=1777']
|
||||
cpus: 0.75
|
||||
mem_limit: 192m
|
||||
|
||||
x-app: &app
|
||||
<<: *hardening
|
||||
image: mtusi-messenger:lab7
|
||||
build: .
|
||||
mem_limit: 384m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 12s
|
||||
|
||||
x-app-env: &app-env
|
||||
POSTGRES_HOST: postgres
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_MAX_CONNS: '8'
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
S3_ENDPOINT: minio:9000
|
||||
S3_USE_SSL: 'true'
|
||||
SSL_CERT_FILE: /trust/ca.crt
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://collector:44318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
OTEL_TRACES_SAMPLER: parentbased_traceidratio
|
||||
OTEL_TRACES_SAMPLER_ARG: '1.0'
|
||||
GOMEMLIMIT: 224MiB
|
||||
GOGC: '50'
|
||||
|
||||
x-proxy: &proxy
|
||||
<<: *hardening
|
||||
user: '10001:10001'
|
||||
image: mtusi-messenger:lab7
|
||||
entrypoint: [/usr/local/bin/tlsproxy]
|
||||
restart: on-failure
|
||||
cpus: 0.25
|
||||
mem_limit: 48m
|
||||
|
||||
services:
|
||||
postgres:
|
||||
<<: *hardening
|
||||
image: postgres:17-alpine@sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73
|
||||
user: postgres
|
||||
entrypoint: [/bin/sh, /postgres-entrypoint.sh]
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /bootstrap/POSTGRES_PASSWORD
|
||||
tmpfs: ['/tmp:size=16m,mode=1777', '/var/run/postgresql:size=8m,mode=1777']
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./.runtime/identities/postgres:/identity:ro
|
||||
- ./.runtime/bootstrap/admin:/bootstrap:ro
|
||||
- ./infra/postgres-entrypoint.sh:/postgres-entrypoint.sh:ro
|
||||
- ./infra/pg_hba.conf:/etc/pg_hba.conf:ro
|
||||
- ./infra/pg_ident.conf:/etc/pg_ident.conf:ro
|
||||
healthcheck:
|
||||
test: [CMD-SHELL, 'pg_isready -h postgres -U messenger -d messenger']
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 30
|
||||
networks: [data]
|
||||
|
||||
migrations:
|
||||
<<: *hardening
|
||||
image: mtusi-migrations:lab7
|
||||
build: {context: ., target: migrations}
|
||||
profiles: [operator]
|
||||
environment:
|
||||
GOOSE_DRIVER: postgres
|
||||
GOOSE_DBSTRING: host=postgres user=messenger dbname=messenger sslmode=verify-full sslrootcert=/trust/ca.crt connect_timeout=5
|
||||
POSTGRES_PASSWORD_FILE: /bootstrap/admin/POSTGRES_PASSWORD
|
||||
volumes:
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/bootstrap/admin:/bootstrap/admin:ro
|
||||
networks: [data]
|
||||
|
||||
db_grants:
|
||||
<<: *hardening
|
||||
image: postgres:17-alpine@sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73
|
||||
profiles: [operator]
|
||||
user: postgres
|
||||
entrypoint: [/bin/sh, /grant.sh]
|
||||
environment: {PGSSLROOTCERT: /trust/ca.crt, PGSSLMODE: verify-full}
|
||||
volumes:
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/bootstrap:/bootstrap:ro
|
||||
- ./infra/db-grants.sql:/grants.sql:ro
|
||||
- ./infra/rotate-worker.sql:/rotate-worker.sql:ro
|
||||
- ./.runtime/retired:/retired:ro
|
||||
- ./infra/db-grants.sh:/grant.sh:ro
|
||||
- ./security/db-audit.sh:/db-audit.sh:ro
|
||||
networks: [data]
|
||||
|
||||
redis:
|
||||
<<: *hardening
|
||||
image: redis:7.4-alpine@sha256:7f7d30b7fdd09467bac58198a1f166dd69789d348d4fe859cccb20e0cf287fbe
|
||||
user: redis
|
||||
command: [redis-server, /etc/redis.conf]
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
- ./infra/redis.conf:/etc/redis.conf:ro
|
||||
- ./.runtime/redis:/acl:ro
|
||||
networks: [data]
|
||||
|
||||
redis_tls:
|
||||
<<: *proxy
|
||||
network_mode: service:redis
|
||||
environment: {TLS_ROUTES: '6380=6379=api;6381=6379=worker;6382=6379=operator'}
|
||||
volumes:
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/redis:/identity:ro
|
||||
|
||||
minio:
|
||||
<<: *hardening
|
||||
image: mtusi-lab7-minio:RELEASE.2025-09-07T16-13-09Z
|
||||
build: {context: ., dockerfile: Dockerfile.storage, target: minio}
|
||||
environment: {GOMEMLIMIT: 112MiB, GOGC: '50'}
|
||||
mem_limit: 256m
|
||||
stop_grace_period: 15s
|
||||
volumes:
|
||||
- s3_data:/data
|
||||
- ./.runtime/bootstrap/admin:/bootstrap:ro
|
||||
- ./.runtime/identities/minio:/identity:ro
|
||||
networks: [data]
|
||||
|
||||
s3_bootstrap:
|
||||
<<: *hardening
|
||||
image: mtusi-lab7-mc:RELEASE.2025-08-13T08-35-41Z
|
||||
build: {context: ., dockerfile: Dockerfile.storage, target: mc}
|
||||
profiles: [operator]
|
||||
entrypoint: [/bin/sh, /bootstrap.sh]
|
||||
volumes:
|
||||
- ./infra/s3-bootstrap.sh:/bootstrap.sh:ro
|
||||
- ./.runtime/retired:/retired:ro
|
||||
- ./security/s3-audit.sh:/s3-audit.sh:ro
|
||||
- ./infra/s3-api.json:/policies/s3-api.json:ro
|
||||
- ./infra/s3-worker.json:/policies/s3-worker.json:ro
|
||||
- ./infra/s3-operator.json:/policies/s3-operator.json:ro
|
||||
- ./.runtime/bootstrap:/bootstrap:ro
|
||||
- ./.runtime/trust:/trust:ro
|
||||
networks: [data]
|
||||
|
||||
openbao:
|
||||
<<: *hardening
|
||||
image: openbao/openbao:2.6.1@sha256:5b2486ab0fb90bbc788cc345b0a08616dfb375873ee8be5df3a2fd4d378a67e0
|
||||
user: '100:1000'
|
||||
entrypoint: [bao, server, -config=/etc/bao.hcl]
|
||||
ports: ['127.0.0.1:18200:8200']
|
||||
volumes:
|
||||
- openbao_data:/openbao/file
|
||||
- ./infra/openbao/bao.hcl:/etc/bao.hcl:ro
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/openbao:/identity:ro
|
||||
networks: [data]
|
||||
|
||||
api:
|
||||
<<: *app
|
||||
environment:
|
||||
<<: *app-env
|
||||
SERVICE_ROLE: api
|
||||
POSTGRES_USER: messenger_api
|
||||
REDIS_USER: api
|
||||
REDIS_ADDR: redis:6380
|
||||
volumes:
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/api:/identity:ro
|
||||
deploy: {replicas: 2}
|
||||
networks: [ingress, data, telemetry]
|
||||
|
||||
worker:
|
||||
<<: *app
|
||||
entrypoint: [/usr/local/bin/worker]
|
||||
environment:
|
||||
<<: *app-env
|
||||
SERVICE_ROLE: worker
|
||||
POSTGRES_USER: messenger_worker
|
||||
REDIS_USER: worker
|
||||
REDIS_ADDR: redis:6381
|
||||
WORKER_CONCURRENCY: '2'
|
||||
WORKER_PREFETCH: '4'
|
||||
WORKER_MAX_ATTEMPTS: '5'
|
||||
WORKER_TIMEOUT_SECONDS: '25'
|
||||
WORKER_LEASE_SECONDS: '40'
|
||||
WORKER_PIXEL_BUDGET: '40000000'
|
||||
volumes:
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/worker:/identity:ro
|
||||
networks: [data, telemetry]
|
||||
|
||||
operator:
|
||||
<<: *app
|
||||
profiles: [operator]
|
||||
restart: 'no'
|
||||
entrypoint: [/usr/local/bin/reconcile]
|
||||
environment:
|
||||
<<: *app-env
|
||||
SERVICE_ROLE: operator
|
||||
POSTGRES_USER: messenger_operator
|
||||
REDIS_USER: operator
|
||||
REDIS_ADDR: redis:6382
|
||||
OTEL_SDK_DISABLED: 'true'
|
||||
volumes:
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/operator:/identity:ro
|
||||
networks: [data]
|
||||
|
||||
gateway:
|
||||
<<: *hardening
|
||||
image: haproxy:3.2-alpine@sha256:7816a9801a6846b912bc37e48529808e2fa87c3c47992441940f68e393ebcfeb
|
||||
user: '10001:10001'
|
||||
ports: ['127.0.0.1:${PORT:-8443}:8443']
|
||||
volumes:
|
||||
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/gateway:/identity:ro
|
||||
depends_on: [api]
|
||||
mem_limit: 64m
|
||||
networks: [ingress]
|
||||
|
||||
collector:
|
||||
<<: *hardening
|
||||
image: otel/opentelemetry-collector-contrib:0.137.0
|
||||
command: [--config=/etc/otelcol/config.yaml]
|
||||
volumes:
|
||||
- ./infra/otel/collector.yaml:/etc/otelcol/config.yaml:ro
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/collector:/identity:ro
|
||||
networks: [telemetry]
|
||||
|
||||
collector_tls:
|
||||
<<: *proxy
|
||||
network_mode: service:collector
|
||||
environment: {TLS_ROUTES: '44318=4318=api worker=POST:/v1/;48888=8888=prometheus=GET:/metrics;48889=8889=prometheus=GET:/metrics'}
|
||||
volumes:
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/collector:/identity:ro
|
||||
|
||||
prometheus:
|
||||
<<: *hardening
|
||||
image: prom/prometheus:v3.6.0
|
||||
command: [--config.file=/etc/prometheus/prometheus.yaml, --storage.tsdb.retention.time=7d, --storage.tsdb.retention.size=1GB, --web.listen-address=127.0.0.1:9090]
|
||||
volumes:
|
||||
- ./infra/prometheus:/etc/prometheus:ro
|
||||
- prometheus_data:/prometheus
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/prometheus:/identity:ro
|
||||
networks: [telemetry]
|
||||
|
||||
prometheus_tls:
|
||||
<<: *proxy
|
||||
network_mode: service:prometheus
|
||||
environment: {TLS_ROUTES: '49090=9090=grafana=GET:/api/v1/query,GET:/api/v1/query_range,GET:/api/v1/series,GET:/api/v1/labels,GET:/api/v1/label/,GET:/api/v1/status/buildinfo,POST:/api/v1/query,POST:/api/v1/query_range,POST:/api/v1/series,POST:/api/v1/labels'}
|
||||
volumes:
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/prometheus:/identity:ro
|
||||
|
||||
loki:
|
||||
<<: *hardening
|
||||
image: grafana/loki:3.5.5
|
||||
command: [-config.file=/etc/loki/config.yaml]
|
||||
volumes:
|
||||
- ./infra/loki.yaml:/etc/loki/config.yaml:ro
|
||||
- loki_data:/loki
|
||||
networks: [telemetry]
|
||||
|
||||
loki_tls:
|
||||
<<: *proxy
|
||||
network_mode: service:loki
|
||||
environment: {TLS_ROUTES: '43100=3100=collector=POST:/otlp/v1/logs;43101=3100=grafana=GET:/loki/api/v1/query,GET:/loki/api/v1/query_range,GET:/loki/api/v1/labels,GET:/loki/api/v1/label/,GET:/loki/api/v1/series,GET:/loki/api/v1/status/buildinfo;43102=3100=prometheus=GET:/metrics'}
|
||||
volumes:
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/loki:/identity:ro
|
||||
|
||||
tempo:
|
||||
<<: *hardening
|
||||
image: grafana/tempo:2.8.2
|
||||
command: [-config.file=/etc/tempo/config.yaml]
|
||||
volumes:
|
||||
- ./infra/tempo.yaml:/etc/tempo/config.yaml:ro
|
||||
- tempo_data:/var/tempo
|
||||
environment: {GOMEMLIMIT: 300MiB, GOGC: '50'}
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
networks: [telemetry]
|
||||
|
||||
tempo_tls:
|
||||
<<: *proxy
|
||||
network_mode: service:tempo
|
||||
environment: {TLS_ROUTES: '44318=4318=collector=POST:/v1/traces;43200=3200=grafana=GET:/api/;43201=3200=prometheus=GET:/metrics'}
|
||||
volumes:
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities/tempo:/identity:ro
|
||||
|
||||
grafana:
|
||||
<<: *hardening
|
||||
image: grafana/grafana:12.2.0
|
||||
ports: ['127.0.0.1:13000:3000']
|
||||
environment:
|
||||
GF_SERVER_PROTOCOL: https
|
||||
GF_SERVER_CERT_FILE: /identity/tls.crt
|
||||
GF_SERVER_CERT_KEY: /identity/tls.key
|
||||
GF_SERVER_ROOT_URL: https://localhost:13000/
|
||||
GF_PATHS_PROVISIONING: /provisioning
|
||||
GF_SECURITY_ADMIN_PASSWORD__FILE: /bootstrap/GRAFANA_PASSWORD
|
||||
GF_SECURITY_COOKIE_SECURE: 'true'
|
||||
GF_PLUGINS_PREINSTALL_DISABLED: 'true'
|
||||
GF_ANALYTICS_CHECK_FOR_UPDATES: 'false'
|
||||
GF_ANALYTICS_REPORTING_ENABLED: 'false'
|
||||
GF_USERS_ALLOW_SIGN_UP: 'false'
|
||||
volumes:
|
||||
- ./.runtime/grafana:/provisioning:ro
|
||||
- ./.runtime/identities/grafana:/identity:ro
|
||||
- ./.runtime/bootstrap/grafana:/bootstrap:ro
|
||||
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
- grafana_data:/var/lib/grafana
|
||||
networks: [telemetry]
|
||||
|
||||
audit:
|
||||
<<: *hardening
|
||||
image: python:3.13.9-alpine3.22
|
||||
profiles: [operator]
|
||||
user: '10001:10001'
|
||||
entrypoint: [python, /audit.py]
|
||||
volumes:
|
||||
- ./security/audit.py:/audit.py:ro
|
||||
- ./.runtime/trust:/trust:ro
|
||||
- ./.runtime/identities:/identities:ro
|
||||
- ./.runtime/bootstrap:/bootstrap:ro
|
||||
- ./.runtime/retired:/retired:ro
|
||||
networks: [ingress, data, telemetry]
|
||||
|
||||
networks:
|
||||
ingress: {}
|
||||
data: {}
|
||||
telemetry: {}
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
s3_data:
|
||||
openbao_data:
|
||||
prometheus_data:
|
||||
loki_data:
|
||||
tempo_data:
|
||||
grafana_data:
|
||||
@@ -0,0 +1,9 @@
|
||||
package contracts
|
||||
|
||||
import _ "embed"
|
||||
|
||||
// OpenAPI is embedded so Swagger UI works from a compiled binary and does not
|
||||
// depend on the process working directory.
|
||||
//
|
||||
//go:embed openapi.json
|
||||
var OpenAPI []byte
|
||||
+23
-32
@@ -1,37 +1,28 @@
|
||||
# Матрица доверия — заполнить в решении lab7
|
||||
# Матрица доверия
|
||||
|
||||
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
||||
У стенда свой CA. Конфигурация использует TLS 1.2 или новее. Клиент проверяет цепочку и DNS SAN сервера. Имена в таблице совпадают с DNS Compose. Клиентский URI SAN имеет вид `spiffe://mtusi.lab/<роль>`. Сертификаты ролей действуют 7 суток. CA действует 180 суток. OpenBao выдаёт токен на 30 секунд при каждой проверке доступа к секретам. Пароли PostgreSQL, Redis и ключи S3 статические до ротации. [Настройки Compose](../compose.yaml) · [Операторские команды](../REPORT.md)
|
||||
|
||||
| Связь | Минимум на 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 |
|
||||
| Связь и порт | Идентичность и права | Проверка |
|
||||
| --- | --- | --- |
|
||||
| Клиент → HAProxy, `localhost:8443` | TLS, SAN `localhost` или IP SAN `127.0.0.1`. Basic при входе, Bearer на защищённых маршрутах. TTL сессии 1 час. | `make test`, `make test-security`, `http_checks.py rate/expiry/authorization`. `audit matrix` проверяет чужой hostname. |
|
||||
| HAProxy → обе API-реплики, `api:8080` | mTLS. HAProxy проверяет SAN `api`. API принимает только URI SAN `gateway` и проверяет серийный номер. Readiness использует тот же listener. | `audit matrix` проверяет обе реплики. Отклоняются пустая цепочка, чужой CA, `outsider` и `worker`. |
|
||||
| API/worker → PostgreSQL, `postgres:5432` | TLS `verify-full`, SCRAM-SHA-256. Роли `messenger_api`, `messenger_worker`, `messenger_operator` имеют свои пароли и права. | `db-audit.sh` проверяет TLS по `pg_stat_ssl` и отказ plaintext. Проверяет SELECT/UPDATE разрешённых полей и отказы для чужих таблиц и DDL. |
|
||||
| API/worker → MinIO, `minio:9000` | TLS, SigV4. API пишет в `staging/` и читает `original/`. Worker читает и очищает `staging/`, обслуживает `original/`. | `s3-audit.sh` использует обе роли. Проверяет отказы для чужого префикса, записи в staging от worker и S3 admin. |
|
||||
| API/worker → Redis, `redis:6380/6381` | mTLS. Порт 6380 принимает только `api`, 6381 только `worker`. Redis проверяет отдельные ACL-пароли. API публикует задачи и обслуживает сессии. Worker читает очередь и подтверждает задачи. | `audit matrix` проверяет четыре неверных identity. `audit worker` проверяет чужую очередь, сессии, публикацию и административную команду. |
|
||||
| API → Redis для сессий и лимитов, `redis:6380` | Тот же mTLS. ACL API ограничивает доступ ключами `session:*`, `login:*` и одним stream. | `http_checks.py rate`, `audit worker`. Logout проверяет публичный smoke. |
|
||||
| API/worker → Collector, `collector:44318` | mTLS, URI SAN `api` или `worker`. Прокси принимает OTLP HTTP POST. | `audit matrix` проверяет обе роли. Пустая цепочка, чужой CA и `outsider` отклоняются. `audit rotation` проверяет отзыв. |
|
||||
| Collector → Loki/Tempo, `loki:43100`, `tempo:44318` | mTLS, только `collector`. Разрешены POST `/otlp/v1/logs` и POST `/v1/traces`. Prometheus забирает метрики отдельно. | `audit matrix` проверяет OTLP и отказ для `grafana`. `http_checks.py telemetry` проверяет реальные записи. |
|
||||
| Prometheus → Collector/Loki/Tempo, порты `48888`, `48889`, `43102`, `43201` | mTLS, URI SAN `prometheus`, только GET `/metrics`. Самосбор Prometheus использует loopback. | `audit matrix` проверяет сбор с каждой цели и отказ для worker. |
|
||||
| Grafana → Prometheus/Loki/Tempo, порты `49090`, `43101`, `43200` | mTLS, URI SAN `grafana`. Список HTTP-операций разрешает запросы к данным. | `audit matrix` проверяет чтение, отказ для worker и запрет записи метрик и логов. |
|
||||
| API/worker/operator → OpenBao, `openbao:8200` | TLS с проверкой SAN. Cert auth проверяет конкретный сертификат и URI SAN. Политика даёт чтение одного KV-пути и отзыв своего токена. | `audit bao-expiry` проверяет TTL, чужой путь и запись политик. `audit rotation` проверяет старый сертификат worker. |
|
||||
| Оператор → OpenBao, Grafana, MinIO | OpenBao `localhost:18200` принимает TLS и токен оператора. Grafana `localhost:13000` использует TLS и отдельный пароль. MinIO admin доступен из сети данных. | `audit matrix` проверяет отказ анонимной Grafana и S3. `s3-audit.sh` проверяет запрет S3 admin для worker. |
|
||||
| Служебные команды и health | Goose, GRANT и S3 bootstrap проверяют CA/SAN. PostgreSQL health проверяет доступность порта. HAProxy проверяет полную готовность через mTLS. | Bootstrap, публичный smoke и `audit matrix`. |
|
||||
| Кластеры хранилищ | В Compose один экземпляр каждого хранилища. API реплики используют общее состояние. | `make test-failover`, `make test-persistence`. |
|
||||
|
||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
||||
`audit` запускает оператор через `./scripts/compose.sh run --rm --no-deps audit <проверка>`.
|
||||
Прокси и компонент делят сетевое пространство имён. Открытый протокол доступен только на `127.0.0.1` внутри этого пространства.
|
||||
У Redis и Collector порты открытого протокола закрыты для других контейнеров. Тот же тест проверяет Loki, Tempo и Prometheus.
|
||||
|
||||
## Обязательные отрицательные проверки
|
||||
Список отозванных серийных номеров действует на новых TLS-соединениях. Прокси отключают TLS resumption. Redis ограничивает открытое соединение 90 секундами. Ротация дополнительно завершает соединения пользователя `worker` командой `CLIENT KILL`.
|
||||
|
||||
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
|
||||
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех.
|
||||
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity.
|
||||
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
|
||||
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
|
||||
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
|
||||
|
||||
## Bootstrap и эксплуатация
|
||||
|
||||
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
|
||||
|
||||
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.
|
||||
Приложения перечитывают OpenBao каждые 10 секунд. Продолжают работу до 35 секунд после последнего успешного чтения. Очередная проверка обнаруживает истечение лимита. На защиту от копирования пароля напрямую влияют ACL и ротация конкретного компонента.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package dto
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type CreateChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package dto
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
ChatID string `json:"-"`
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type CreateMessageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Keep absent attachment_ids equivalent to [], while rejecting JSON null and
|
||||
// wrong types rather than quietly treating them as an empty message body.
|
||||
func (r *CreateMessageRequest) UnmarshalJSON(data []byte) error {
|
||||
type payload CreateMessageRequest
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &fields); err != nil || fields == nil {
|
||||
return errors.New("Ожидается JSON-объект")
|
||||
}
|
||||
text, exists := fields["text"]
|
||||
if !exists || bytes.Equal(bytes.TrimSpace(text), []byte("null")) {
|
||||
return errors.New("Требуется строка text")
|
||||
}
|
||||
if ids, exists := fields["attachment_ids"]; exists && bytes.Equal(bytes.TrimSpace(ids), []byte("null")) {
|
||||
return errors.New("attachment_ids должен быть массивом")
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
decoder.DisallowUnknownFields()
|
||||
var decoded payload
|
||||
if err := decoder.Decode(&decoded); err != nil {
|
||||
return err
|
||||
}
|
||||
decoded.ChatID = r.ChatID
|
||||
*r = CreateMessageRequest(decoded)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMessageStrictFields(t *testing.T) {
|
||||
for _, body := range []string{`null`, `[]`, `{}`, `{"text":null}`, `{"text":"x","attachment_ids":null}`, `{"text":"x","attachment_ids":"x"}`, `{"text":"x","extra":1}`} {
|
||||
var r CreateMessageRequest
|
||||
if err := json.Unmarshal([]byte(body), &r); err == nil {
|
||||
t.Fatalf("accepted %s", body)
|
||||
}
|
||||
}
|
||||
for _, body := range []string{`{"text":"x"}`, `{"text":"x","attachment_ids":[]}`, `{"text":"","attachment_ids":["id"]}`} {
|
||||
var r CreateMessageRequest
|
||||
if err := json.Unmarshal([]byte(body), &r); err != nil {
|
||||
t.Fatalf("rejected %s: %v", body, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package dto
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Password string `json:"password"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
|
||||
type CreateUserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package dto
|
||||
|
||||
type CurrentUserRequest struct{}
|
||||
|
||||
type CurrentUserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package dto
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error ErrorDetails `json:"error"`
|
||||
}
|
||||
|
||||
type ErrorDetails struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package dto
|
||||
|
||||
type GetChatRequest struct {
|
||||
ChatID string `json:"-"`
|
||||
}
|
||||
|
||||
type GetChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package dto
|
||||
|
||||
type ListChatsRequest struct {
|
||||
Limit int `json:"-"`
|
||||
Cursor string `json:"-"`
|
||||
}
|
||||
|
||||
type ListChatsResponse struct {
|
||||
Items []ListChatsItem `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type ListChatsItem struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dto
|
||||
|
||||
type ListMessagesRequest struct {
|
||||
ChatID string `json:"-"`
|
||||
Limit int `json:"-"`
|
||||
Cursor string `json:"-"`
|
||||
}
|
||||
|
||||
type ListMessagesResponse struct {
|
||||
Items []ListMessagesItem `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type ListMessagesItem struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package dto
|
||||
|
||||
type LivenessRequest struct{}
|
||||
|
||||
type LivenessResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package dto
|
||||
|
||||
type ReadinessRequest struct{}
|
||||
|
||||
type ReadinessResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package dto
|
||||
|
||||
type CreateSessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt Timestamp `json:"expires_at"`
|
||||
User CreateUserResponse `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
// Timestamp preserves PostgreSQL microseconds and is readable by Python 3.9 clients.
|
||||
// time.Time's variable-length fractional part is not supported by those clients.
|
||||
type Timestamp time.Time
|
||||
|
||||
func (t Timestamp) MarshalJSON() ([]byte, error) {
|
||||
return []byte(`"` + time.Time(t).UTC().Format("2006-01-02T15:04:05.000000Z") + `"`), nil
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTimestampFixedMicroseconds(t *testing.T) {
|
||||
timestamp := Timestamp(time.Date(2026, 1, 2, 3, 4, 5, 123400000, time.UTC))
|
||||
encoded, err := json.Marshal(timestamp)
|
||||
if err != nil || string(encoded) != `"2026-01-02T03:04:05.123400Z"` {
|
||||
t.Fatalf("timestamp=%s err=%v", encoded, err)
|
||||
}
|
||||
}
|
||||
+12
-3
@@ -1,5 +1,14 @@
|
||||
# Доказательства
|
||||
# Результаты проверок
|
||||
|
||||
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
|
||||
- `smoke.txt` и `go-test.txt` содержат вывод проверок приложения и контракта.
|
||||
- `tls-audit.txt`, `openbao-expiry.txt`, `openbao-bootstrap.txt`, `http-security.txt` и `seal.json` содержат результаты проверок безопасности.
|
||||
- `hardening.jsonl` содержит настройки ограничений действующих контейнеров.
|
||||
- `persistence.txt`, `failover.txt` и файлы `*-containers.txt` содержат вывод тестов и состояние контейнеров до и после отказов.
|
||||
- `worker-experiment.json` содержит результат трёх повторов. `worker-access.txt` содержит проверки прав и отзыва. Файлы `worker-final-stack*` относятся к дополнительному прогону на пересобранном MinIO.
|
||||
- `argon2.txt` содержит микробенчмарк проверки пароля.
|
||||
- `tempo-recovery.txt` содержит проверку сбора телеметрии после восстановления Tempo.
|
||||
- `mc-verification.txt` содержит версию утилиты и проверку прав S3.
|
||||
- `lab7-verification.txt` и `lab7-verification-worker.json` содержат результаты повторной проверки нового функционала.
|
||||
- `scan-triage.md` содержит результаты сканирования и анализ применимости.
|
||||
|
||||
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
|
||||
Команды, условия эксперимента и ограничения приведены в отчёте. [Отчёт](../REPORT.md)
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
goos: darwin
|
||||
goarch: arm64
|
||||
pkg: gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password
|
||||
cpu: Apple M1 Pro
|
||||
BenchmarkVerify-8 32 32857975 ns/op
|
||||
BenchmarkVerify-8 37 31957708 ns/op
|
||||
BenchmarkVerify-8 37 32891991 ns/op
|
||||
PASS
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password 4.294s
|
||||
@@ -0,0 +1,7 @@
|
||||
mtusi2026lab7-postgres-1 postgres: sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73
|
||||
mtusi2026lab7-minio-1 mtusi-lab7-minio:RELEASE.2025-09-07T16-13-09Z sha256:23ca84fbe6b325408bebcae09af30d0793a8b22df7a8706aeeaf5c4053f4c62b
|
||||
mtusi2026lab7-api-2 mtusi-messenger:lab7 sha256:db4a3aab8e56b5ffc6352d1d35bcbcf242b38b05d711b26308277f67fc6af082
|
||||
mtusi2026lab7-worker-1 mtusi-messenger:lab7 sha256:db4a3aab8e56b5ffc6352d1d35bcbcf242b38b05d711b26308277f67fc6af082
|
||||
mtusi2026lab7-api-1 mtusi-messenger:lab7 sha256:db4a3aab8e56b5ffc6352d1d35bcbcf242b38b05d711b26308277f67fc6af082
|
||||
mtusi2026lab7-openbao-1 openbao/openbao: sha256:5b2486ab0fb90bbc788cc345b0a08616dfb375873ee8be5df3a2fd4d378a67e0
|
||||
mtusi2026lab7-redis-1 redis: sha256:7f7d30b7fdd09467bac58198a1f166dd69789d348d4fe859cccb20e0cf287fbe
|
||||
@@ -0,0 +1,2 @@
|
||||
/mtusi2026lab7-api-2 hostname=d00541bf8861 status=exited stopped=2026-11-27T16:49:46.429730427Z
|
||||
/mtusi2026lab7-api-1 hostname=4947f19d488b status=exited stopped=2026-11-27T16:50:03.979200877Z
|
||||
@@ -0,0 +1,8 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "https://localhost:8443" --ca-file "/Users/dkhakimovig/mtusi2026lab7/.runtime/trust/ca.crt"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 102, "failed_attempts": 2, "first_recovery_seconds": 3.481}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "https://localhost:8443" --ca-file "/Users/dkhakimovig/mtusi2026lab7/.runtime/trust/ca.crt"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 106, "failed_attempts": 6, "first_recovery_seconds": 3.361}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,40 @@
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd [no test files]
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd/reconcile [no test files]
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd/tlsproxy [no test files]
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd/worker [no test files]
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/contracts [no test files]
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/dto (cached)
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat (cached)
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment (cached)
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config [no test files]
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/observability (cached)
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain [no test files]
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password (cached)
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository [no test files]
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres (cached)
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/session [no test files]
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/trust [no test files]
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat (cached)
|
||||
../mtusi2026lab6/.venv/bin/python scripts/validate_openapi.py
|
||||
/Users/dkhakimovig/mtusi2026lab6/.venv/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.
|
||||
|
||||
go test -race ./...
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd [no test files]
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd/reconcile [no test files]
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd/tlsproxy [no test files]
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/cmd/worker [no test files]
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/contracts [no test files]
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/dto 1.303s
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat 12.211s
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment 1.552s
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config [no test files]
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/observability 1.385s
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain [no test files]
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password 3.277s
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository [no test files]
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres 1.476s
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/session [no test files]
|
||||
? gitflic.ru/akselbant/mtusi2026lab1-fork/internal/trust [no test files]
|
||||
ok gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat 1.977s
|
||||
@@ -0,0 +1,18 @@
|
||||
{"name": "/mtusi2026lab7-api-1", "user": "messenger:messenger", "memory": 402653184, "cpus": 750000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-api-2", "user": "messenger:messenger", "memory": 402653184, "cpus": 750000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-collector-1", "user": "10001:10001", "memory": 201326592, "cpus": 750000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-collector_tls-1", "user": "10001:10001", "memory": 50331648, "cpus": 250000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-gateway-1", "user": "10001:10001", "memory": 67108864, "cpus": 750000000, "readonly": true, "ports": {"8443/tcp": [{"HostIp": "127.0.0.1", "HostPort": "8443"}]}}
|
||||
{"name": "/mtusi2026lab7-grafana-1", "user": "472", "memory": 201326592, "cpus": 750000000, "readonly": true, "ports": {"3000/tcp": [{"HostIp": "127.0.0.1", "HostPort": "13000"}]}}
|
||||
{"name": "/mtusi2026lab7-loki-1", "user": "10001", "memory": 201326592, "cpus": 750000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-loki_tls-1", "user": "10001:10001", "memory": 50331648, "cpus": 250000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-minio-1", "user": "10001:10001", "memory": 268435456, "cpus": 750000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-openbao-1", "user": "100:1000", "memory": 201326592, "cpus": 750000000, "readonly": true, "ports": {"8200/tcp": [{"HostIp": "127.0.0.1", "HostPort": "18200"}]}}
|
||||
{"name": "/mtusi2026lab7-postgres-1", "user": "postgres", "memory": 201326592, "cpus": 750000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-prometheus-1", "user": "nobody", "memory": 201326592, "cpus": 750000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-prometheus_tls-1", "user": "10001:10001", "memory": 50331648, "cpus": 250000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-redis-1", "user": "redis", "memory": 201326592, "cpus": 750000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-redis_tls-1", "user": "10001:10001", "memory": 50331648, "cpus": 250000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-tempo-1", "user": "10001:10001", "memory": 536870912, "cpus": 750000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-tempo_tls-1", "user": "10001:10001", "memory": 50331648, "cpus": 250000000, "readonly": true, "ports": {}}
|
||||
{"name": "/mtusi2026lab7-worker-1", "user": "messenger:messenger", "memory": 402653184, "cpus": 750000000, "readonly": true, "ports": {}}
|
||||
@@ -0,0 +1,4 @@
|
||||
PASS cross-chat attachment, spoofed identity and oversized upload denied
|
||||
{"limit_scope": "shared between replicas", "replicas": 2, "account_window": 30, "kdf_http_ms": [211.4, 93.1, 117.7, 119.9, 172.0, 192.7, 172.1, 291.8], "allowed": 8, "http_429": 2}
|
||||
PASS correlated login logs, traces and metrics present; no credential canaries
|
||||
PASS session expiry enforced with a previously valid token
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"docker_platform": "linux/aarch64",
|
||||
"docker_vcpus": 2,
|
||||
"docker_memory_bytes": 2054832128,
|
||||
"fixture_png_bytes": 111817,
|
||||
"closed_loop_concurrency": 4,
|
||||
"queue_observation_seconds": 2,
|
||||
"runs": [
|
||||
{
|
||||
"worker_image_id": "sha256:db4a3aab8e56b5ffc6352d1d35bcbcf242b38b05d711b26308277f67fc6af082",
|
||||
"baseline": {
|
||||
"jobs": 8,
|
||||
"verified": 8,
|
||||
"ready_latency": {
|
||||
"p50_ms": 515.0,
|
||||
"p95_ms": 866.7,
|
||||
"p99_ms": 866.7
|
||||
},
|
||||
"read_retries": 0,
|
||||
"worker_sample": {
|
||||
"cpu": "34.46%",
|
||||
"memory": "21.99MiB / 384MiB"
|
||||
},
|
||||
"submission_latency": {
|
||||
"p50_ms": 67.2,
|
||||
"p95_ms": 115.7,
|
||||
"p99_ms": 115.7
|
||||
},
|
||||
"verified_per_second": 8.08
|
||||
},
|
||||
"incident": {
|
||||
"queued": 8,
|
||||
"verified": 8,
|
||||
"lost_or_duplicate": 0,
|
||||
"submission_latency": {
|
||||
"p50_ms": 69.4,
|
||||
"p95_ms": 136.6,
|
||||
"p99_ms": 136.6
|
||||
},
|
||||
"ready_latency": {
|
||||
"p50_ms": 34598.4,
|
||||
"p95_ms": 34921.9,
|
||||
"p99_ms": 34921.9
|
||||
},
|
||||
"read_retries": 0,
|
||||
"rotation_seconds": 31.56,
|
||||
"worker_unavailable_seconds": 35.08,
|
||||
"drain_seconds_after_start": 1.19
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
2026-11-29 Lab 7 verification
|
||||
python3 tests/security.py --base-url "https://localhost:8443" --ca-file ".runtime/trust/ca.crt"
|
||||
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||
PASS cross-chat attachment, spoofed identity and oversized upload denied
|
||||
{"limit_scope": "shared between replicas", "replicas": 2, "account_window": 30, "kdf_http_ms": [71.2, 74.6, 56.9, 51.1, 59.8, 51.5, 80.7, 54.7], "allowed": 8, "http_429": 2}
|
||||
PASS correlated login logs, traces and metrics present; no credential canaries
|
||||
Container mtusi2026lab7-audit-run-a298efd9cfc5 Creating
|
||||
Container mtusi2026lab7-audit-run-a298efd9cfc5 Created
|
||||
PASS API 1 None: SSLV3_ALERT_HANDSHAKE_FAILURE
|
||||
PASS API 1 foreign: TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS API 1 outsider: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS API 1 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS API 1: gateway verified
|
||||
PASS API 2 None: SSLV3_ALERT_HANDSHAKE_FAILURE
|
||||
PASS API 2 foreign: TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS API 2 outsider: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS API 2 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS API 2: gateway verified
|
||||
PASS broker 6380 None: SSLV3_ALERT_HANDSHAKE_FAILURE
|
||||
PASS broker 6380 foreign: TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS broker 6380 outsider: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS broker 6380 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS broker 6381 None: SSLV3_ALERT_HANDSHAKE_FAILURE
|
||||
PASS broker 6381 foreign: TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS broker 6381 outsider: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS broker 6381 api: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS collector None: SSLV3_ALERT_HANDSHAKE_FAILURE
|
||||
PASS collector foreign: TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS collector outsider: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS collector:48888 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS collector:48888 prometheus
|
||||
PASS collector:48889 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS collector:48889 prometheus
|
||||
PASS loki:43102 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS loki:43102 prometheus
|
||||
PASS tempo:43201 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS tempo:43201 prometheus
|
||||
PASS prometheus:49090 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS prometheus:49090 grafana
|
||||
PASS loki:43101 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS loki:43101 grafana
|
||||
PASS tempo:43200 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS tempo:43200 grafana
|
||||
PASS loki ingest wrong identity: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS tempo ingest wrong identity: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS ingress hostname verification
|
||||
PASS redis:6379 local hop closed
|
||||
PASS collector:4318 local hop closed
|
||||
PASS loki:3100 local hop closed
|
||||
PASS tempo:4318 local hop closed
|
||||
PASS tempo:3200 local hop closed
|
||||
PASS prometheus:9090 local hop closed
|
||||
Container mtusi2026lab7-audit-run-31c3b7d4058b Creating
|
||||
Container mtusi2026lab7-audit-run-31c3b7d4058b Created
|
||||
PASS OpenBao token expiry (30s)
|
||||
PASS OpenBao worker own KV allowed, peer KV and policy write denied
|
||||
PASS OpenBao api own KV allowed, peer KV and policy write denied
|
||||
PASS worker can consume queue; publish, foreign queue, sessions and FLUSHALL denied
|
||||
PASS PostgreSQL verified TLS; job read/processing update granted, business data/delete/DDL/plaintext denied.
|
||||
PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.
|
||||
PASS retired worker / broker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS retired worker / Collector: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS renewed leaf, retired identity denied on three channels, old password rejected
|
||||
PASS PostgreSQL verified TLS; job read/processing update granted, business data/delete/DDL/plaintext denied.
|
||||
PASS PostgreSQL rejects the retired worker password.
|
||||
PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.
|
||||
PASS MinIO rejects the retired worker access key.
|
||||
@@ -0,0 +1,6 @@
|
||||
sha256:d38523086ff678e86a6191b197163443a33b6f092e51ae9f54b670163fadebef d6541ea280b73a834b64d4097e21f2be77676104
|
||||
mc version DEVELOPMENT.GOGET (commit-id=DEVELOPMENT.GOGET)
|
||||
Runtime: go1.27.3 linux/arm64
|
||||
Container mtusi2026lab7-s3_bootstrap-run-bcf8b994f2e6 Creating
|
||||
Container mtusi2026lab7-s3_bootstrap-run-bcf8b994f2e6 Created
|
||||
PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.
|
||||
@@ -0,0 +1,2 @@
|
||||
PASS empty OpenBao store: initialized, unsealed, cert auth and isolated KV policies provisioned.
|
||||
PASS persistent stack configuration writes an audit journal.
|
||||
@@ -0,0 +1,5 @@
|
||||
Container mtusi2026lab7-audit-run-4ce46a03e251 Creating
|
||||
Container mtusi2026lab7-audit-run-4ce46a03e251 Created
|
||||
PASS OpenBao token expiry (30s)
|
||||
PASS OpenBao worker own KV allowed, peer KV and policy write denied
|
||||
PASS OpenBao api own KV allowed, peer KV and policy write denied
|
||||
@@ -0,0 +1,38 @@
|
||||
before
|
||||
/mtusi2026lab7-api-1 status=running started=2026-11-27T16:41:28.205383958Z
|
||||
/mtusi2026lab7-api-2 status=running started=2026-11-27T16:41:27.926193579Z
|
||||
/mtusi2026lab7-collector-1 status=running started=2026-11-27T16:36:07.268880787Z
|
||||
/mtusi2026lab7-collector_tls-1 status=running started=2026-11-27T16:41:27.922708764Z
|
||||
/mtusi2026lab7-gateway-1 status=running started=2026-11-27T16:36:09.668903997Z
|
||||
/mtusi2026lab7-grafana-1 status=running started=2026-11-27T16:36:07.341615309Z
|
||||
/mtusi2026lab7-loki-1 status=running started=2026-11-27T16:36:07.917430672Z
|
||||
/mtusi2026lab7-loki_tls-1 status=running started=2026-11-27T16:41:27.925395304Z
|
||||
/mtusi2026lab7-minio-1 status=running started=2026-11-27T16:36:07.310210109Z
|
||||
/mtusi2026lab7-openbao-1 status=running started=2026-11-27T16:39:43.552998715Z
|
||||
/mtusi2026lab7-postgres-1 status=running started=2026-11-27T16:39:39.878808884Z
|
||||
/mtusi2026lab7-prometheus-1 status=running started=2026-11-27T16:36:07.365658367Z
|
||||
/mtusi2026lab7-prometheus_tls-1 status=running started=2026-11-27T16:41:27.920688161Z
|
||||
/mtusi2026lab7-redis-1 status=running started=2026-11-27T16:36:07.395333024Z
|
||||
/mtusi2026lab7-redis_tls-1 status=running started=2026-11-27T16:41:27.921836738Z
|
||||
/mtusi2026lab7-tempo-1 status=running started=2026-11-27T16:36:07.511918724Z
|
||||
/mtusi2026lab7-tempo_tls-1 status=running started=2026-11-27T16:41:27.921389182Z
|
||||
/mtusi2026lab7-worker-1 status=running started=2026-11-27T16:43:39.761549977Z
|
||||
after
|
||||
/mtusi2026lab7-api-1 status=running started=2026-11-27T16:46:19.3733609Z
|
||||
/mtusi2026lab7-api-2 status=running started=2026-11-27T16:46:19.398886497Z
|
||||
/mtusi2026lab7-collector-1 status=running started=2026-11-27T16:46:12.943190222Z
|
||||
/mtusi2026lab7-collector_tls-1 status=running started=2026-11-27T16:46:13.501408153Z
|
||||
/mtusi2026lab7-gateway-1 status=running started=2026-11-27T16:46:16.652167603Z
|
||||
/mtusi2026lab7-grafana-1 status=running started=2026-11-27T16:46:13.412756837Z
|
||||
/mtusi2026lab7-loki-1 status=running started=2026-11-27T16:46:13.616969569Z
|
||||
/mtusi2026lab7-loki_tls-1 status=running started=2026-11-27T16:46:14.174041838Z
|
||||
/mtusi2026lab7-minio-1 status=running started=2026-11-27T16:46:12.836430974Z
|
||||
/mtusi2026lab7-openbao-1 status=running started=2026-11-27T16:46:13.033766768Z
|
||||
/mtusi2026lab7-postgres-1 status=running started=2026-11-27T16:46:13.430777685Z
|
||||
/mtusi2026lab7-prometheus-1 status=running started=2026-11-27T16:46:13.045784125Z
|
||||
/mtusi2026lab7-prometheus_tls-1 status=running started=2026-11-27T16:46:13.69213202Z
|
||||
/mtusi2026lab7-redis-1 status=running started=2026-11-27T16:46:12.944599852Z
|
||||
/mtusi2026lab7-redis_tls-1 status=running started=2026-11-27T16:46:13.511390234Z
|
||||
/mtusi2026lab7-tempo-1 status=running started=2026-11-27T16:46:13.584542535Z
|
||||
/mtusi2026lab7-tempo_tls-1 status=running started=2026-11-27T16:46:14.11889655Z
|
||||
/mtusi2026lab7-worker-1 status=running started=2026-11-27T16:46:16.441581739Z
|
||||
@@ -0,0 +1,3 @@
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "https://localhost:8443" --ca-file "/Users/dkhakimovig/mtusi2026lab7/.runtime/trust/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.
|
||||
@@ -0,0 +1,47 @@
|
||||
# Разбор сканирования
|
||||
|
||||
Trivy 0.67.2 проверил собранный образ `mtusi-messenger:lab7` для linux/arm64 и манифесты Go. API, worker и TLS-прокси используют этот образ. Результаты получены 27 ноября 2026 г. Сценарий сохраняет полный JSON в `.runtime/scans`.
|
||||
|
||||
```sh
|
||||
./scripts/scan.sh mtusi-messenger:lab7
|
||||
```
|
||||
|
||||
| Проверка | Critical | High | Medium | Low | Unknown |
|
||||
| --- | ---: | ---: | ---: | ---: | ---: |
|
||||
| Образ до обновлений | 4 | 46 | 53 | 9 | 2 |
|
||||
| Образ после обновлений | 0 | 0 | 14 | 8 | 1 |
|
||||
| Манифесты Go после обновлений | 0 | 0 | 6 | 4 | 1 |
|
||||
|
||||
Числа учитывают уникальные пары идентификатор уязвимости и пакет. Сканирование итогового образа не обнаружило секреты по правилам Trivy. Сканирование исходного кода и конфигурации runtime проводится отдельными проверками.
|
||||
|
||||
| Находка | Применимость и решение |
|
||||
| --- | --- |
|
||||
| Echo до 4.16.1, CVE-2026-118264 и CVE-2026-118650 | Публичные маршруты вызывают разбор пути Echo. Обновили Echo до 4.16.1. Повторили проверки ACL. |
|
||||
| pgx до 5.9.0, CVE-2026-33815 и CVE-2026-33816 | API и worker обрабатывают ответы PostgreSQL через pgx. Обновили pgx до 5.9.0. Повторили интеграционные проверки. |
|
||||
| Go TLS и x509, CVE-2026-111943 и CVE-2026-97031 | TLS работает на границах стенда. Собрали приложения на Go 1.27.3. Повторили матрицу mTLS. |
|
||||
| Alpine musl и zlib, CVE-2026-107891 и CVE-2026-85091 | В образе есть системные библиотеки и утилиты обработки. Обновили digest Alpine. Trivy подтвердил исправленные версии musl и zlib. |
|
||||
| Echo CVE-2026-118651 и CVE-2026-118653 | Лимит использует имя и общую квоту Redis. Заголовки IP не участвуют в определении квоты. |
|
||||
| Go HTTP/1 CVE-2026-97054 | Доступен путь HTTP/1. HAProxy отклоняет большой Content-Length. Потоковое тело ограничивает API. Остаточный риск DoS сохраняется. |
|
||||
| OpenSSL CVE-2026-107496, CVE-2026-95691 и CVE-2026-95692 | TLS в приложении выполняет стандартная библиотека Go. Сценарии CMS и QUIC в приложении не используются. Для системных библиотек остаётся риск при изменении способов запуска. |
|
||||
| OpenTelemetry CVE-2026-128085 и CVE-2026-81872 | Приложение отправляет ограниченный набор атрибутов. Клиент не управляет текстом лога. При большом количестве запросов остаётся риск нагрузки на SDK. Экспорт использует ограниченные очереди. |
|
||||
|
||||
Оценка применимости опирается на настройки и вызовы приложения. Наличие CVE пакета не подтверждает путь выполнения. Итоговый scan показывает состояние базы Trivy в дату запуска.
|
||||
|
||||
## Образы на границах доверия
|
||||
|
||||
```sh
|
||||
./scripts/scan.sh openbao/openbao:2.6.1 postgres:17-alpine redis:7.4-alpine haproxy:3.2-alpine \
|
||||
mtusi-lab7-minio:RELEASE.2025-09-07T16-13-09Z
|
||||
```
|
||||
|
||||
| Образ | Critical | High | Применимость |
|
||||
| --- | ---: | ---: | --- |
|
||||
| OpenBao 2.4.4, до обновления | 9 | 93 | В образе есть старый Go TLS. Cert auth использует TLS. OpenBao обновили. |
|
||||
| OpenBao 2.6.1 | 0 | 34 | В стенде включены только cert auth, локальный том и KV. Плагины SQL, облачные auth и recovery-mode выключены. Остальные находки требуют сопровождения образа. |
|
||||
| PostgreSQL 17.6, до обновления | 3 | 59 | Обновили до 17.12 в пределах одной основной версии. |
|
||||
| PostgreSQL 17.12 | 1 | 32 | Critical CVE-2025-68121 относится к `gosu`, а TLS принимает сервер PostgreSQL. Контейнер запускается сразу от `postgres`, без переключения пользователя через `gosu`. |
|
||||
| Redis 7.4 | 0 | 2 | Две находки относятся к OpenSSL QUIC. Redis принимает loopback TCP. Внешний слой использует Go TLS поверх TCP. |
|
||||
| HAProxy 3.2 | 0 | 0 | HAProxy принимает TLS 1.2 и новее поверх TCP. |
|
||||
| MinIO на Go 1.27.3 | 4 | 39 | Три Critical относятся к библиотеке уведомлений AMQP. Четвёртая относится к gRPC authz. В стенде разрешены S3 HTTPS и локальная консоль. Уведомления AMQP выключены. |
|
||||
|
||||
Журналы Trivy для этих образов также содержат Medium и Low. Список выше показывает критические и высокие находки. Сценарий без аргументов проверяет весь набор образов Compose. Для стенда сохраняются ограничения из модели угроз. [Модель угроз](../security/THREAT_MODEL.md)
|
||||
@@ -0,0 +1 @@
|
||||
{"sealed_to_unavailable_s": 39.86, "last_ready_after_seal_s": 37.55, "unseal_to_ready_s": 2.59, "previous_session_preserved": true}
|
||||
@@ -0,0 +1,6 @@
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file ".runtime/trust/ca.crt"
|
||||
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||
python3 tests/security.py --base-url "https://localhost:8443" --ca-file ".runtime/trust/ca.crt"
|
||||
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||
@@ -0,0 +1,7 @@
|
||||
2026-11-29 Tempo recovery verification
|
||||
status=running restarts=0 oom=false memory_limit_bytes=536870912
|
||||
tempo-1 | level=info ts=2026-11-29T18:53:49.442546026Z caller=compactor.go:156 msg="compaction cycle complete. No more blocks to compact" tenantID=single-tenant
|
||||
tempo-1 | level=info ts=2026-11-29T18:54:19.443089576Z caller=compactor.go:156 msg="compaction cycle complete. No more blocks to compact" tenantID=single-tenant
|
||||
tempo-1 | level=info ts=2026-11-29T18:54:49.443179566Z caller=compactor.go:156 msg="compaction cycle complete. No more blocks to compact" tenantID=single-tenant
|
||||
mtusi2026lab7-tempo-1 240.2MiB / 512MiB
|
||||
PASS correlated login logs, traces and metrics present; no credential canaries
|
||||
@@ -0,0 +1,46 @@
|
||||
Container mtusi2026lab7-audit-run-5128938ac32d Creating
|
||||
Container mtusi2026lab7-audit-run-5128938ac32d Created
|
||||
PASS API 1 None: SSLV3_ALERT_HANDSHAKE_FAILURE
|
||||
PASS API 1 foreign: TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS API 1 outsider: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS API 1 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS API 1: gateway verified
|
||||
PASS API 2 None: SSLV3_ALERT_HANDSHAKE_FAILURE
|
||||
PASS API 2 foreign: TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS API 2 outsider: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS API 2 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS API 2: gateway verified
|
||||
PASS broker 6380 None: SSLV3_ALERT_HANDSHAKE_FAILURE
|
||||
PASS broker 6380 foreign: TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS broker 6380 outsider: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS broker 6380 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS broker 6381 None: SSLV3_ALERT_HANDSHAKE_FAILURE
|
||||
PASS broker 6381 foreign: TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS broker 6381 outsider: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS broker 6381 api: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS collector None: SSLV3_ALERT_HANDSHAKE_FAILURE
|
||||
PASS collector foreign: TLSV1_ALERT_UNKNOWN_CA
|
||||
PASS collector outsider: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS collector:48888 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS collector:48888 prometheus
|
||||
PASS collector:48889 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS collector:48889 prometheus
|
||||
PASS loki:43102 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS loki:43102 prometheus
|
||||
PASS tempo:43201 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS tempo:43201 prometheus
|
||||
PASS prometheus:49090 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS prometheus:49090 grafana
|
||||
PASS loki:43101 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS loki:43101 grafana
|
||||
PASS tempo:43200 worker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS tempo:43200 grafana
|
||||
PASS loki ingest wrong identity: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS tempo ingest wrong identity: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS ingress hostname verification
|
||||
PASS redis:6379 local hop closed
|
||||
PASS collector:4318 local hop closed
|
||||
PASS loki:3100 local hop closed
|
||||
PASS tempo:4318 local hop closed
|
||||
PASS tempo:3200 local hop closed
|
||||
PASS prometheus:9090 local hop closed
|
||||
@@ -0,0 +1,30 @@
|
||||
PASS worker can consume queue; publish, foreign queue, sessions and FLUSHALL denied
|
||||
PASS PostgreSQL verified TLS; job read/processing update granted, business data/delete/DDL/plaintext denied.
|
||||
PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.
|
||||
PASS retired worker / broker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS retired worker / Collector: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS renewed leaf, retired identity denied on three channels, old password rejected
|
||||
PASS PostgreSQL verified TLS; job read/processing update granted, business data/delete/DDL/plaintext denied.
|
||||
PASS PostgreSQL rejects the retired worker password.
|
||||
PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.
|
||||
PASS MinIO rejects the retired worker access key.
|
||||
PASS worker can consume queue; publish, foreign queue, sessions and FLUSHALL denied
|
||||
PASS PostgreSQL verified TLS; job read/processing update granted, business data/delete/DDL/plaintext denied.
|
||||
PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.
|
||||
PASS retired worker / broker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS retired worker / Collector: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS renewed leaf, retired identity denied on three channels, old password rejected
|
||||
PASS PostgreSQL verified TLS; job read/processing update granted, business data/delete/DDL/plaintext denied.
|
||||
PASS PostgreSQL rejects the retired worker password.
|
||||
PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.
|
||||
PASS MinIO rejects the retired worker access key.
|
||||
PASS worker can consume queue; publish, foreign queue, sessions and FLUSHALL denied
|
||||
PASS PostgreSQL verified TLS; job read/processing update granted, business data/delete/DDL/plaintext denied.
|
||||
PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.
|
||||
PASS retired worker / broker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS retired worker / Collector: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS renewed leaf, retired identity denied on three channels, old password rejected
|
||||
PASS PostgreSQL verified TLS; job read/processing update granted, business data/delete/DDL/plaintext denied.
|
||||
PASS PostgreSQL rejects the retired worker password.
|
||||
PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.
|
||||
PASS MinIO rejects the retired worker access key.
|
||||
@@ -0,0 +1,136 @@
|
||||
{
|
||||
"docker_platform": "linux/aarch64",
|
||||
"docker_vcpus": 2,
|
||||
"docker_memory_bytes": 2054832128,
|
||||
"fixture_png_bytes": 111817,
|
||||
"closed_loop_concurrency": 4,
|
||||
"queue_observation_seconds": 2,
|
||||
"runs": [
|
||||
{
|
||||
"worker_image_id": "sha256:db4a3aab8e56b5ffc6352d1d35bcbcf242b38b05d711b26308277f67fc6af082",
|
||||
"baseline": {
|
||||
"jobs": 8,
|
||||
"verified": 8,
|
||||
"ready_latency": {
|
||||
"p50_ms": 596.7,
|
||||
"p95_ms": 927.4,
|
||||
"p99_ms": 927.4
|
||||
},
|
||||
"read_retries": 0,
|
||||
"worker_sample": {
|
||||
"cpu": "40.97%",
|
||||
"memory": "7.918MiB / 384MiB"
|
||||
},
|
||||
"submission_latency": {
|
||||
"p50_ms": 97.3,
|
||||
"p95_ms": 155.1,
|
||||
"p99_ms": 155.1
|
||||
},
|
||||
"verified_per_second": 7.22
|
||||
},
|
||||
"incident": {
|
||||
"queued": 8,
|
||||
"verified": 8,
|
||||
"lost_or_duplicate": 0,
|
||||
"submission_latency": {
|
||||
"p50_ms": 73.3,
|
||||
"p95_ms": 82.2,
|
||||
"p99_ms": 82.2
|
||||
},
|
||||
"ready_latency": {
|
||||
"p50_ms": 34644.6,
|
||||
"p95_ms": 35043.6,
|
||||
"p99_ms": 35043.6
|
||||
},
|
||||
"read_retries": 0,
|
||||
"rotation_seconds": 31.62,
|
||||
"worker_unavailable_seconds": 35.17,
|
||||
"drain_seconds_after_start": 1.22
|
||||
}
|
||||
},
|
||||
{
|
||||
"worker_image_id": "sha256:db4a3aab8e56b5ffc6352d1d35bcbcf242b38b05d711b26308277f67fc6af082",
|
||||
"baseline": {
|
||||
"jobs": 8,
|
||||
"verified": 8,
|
||||
"ready_latency": {
|
||||
"p50_ms": 678.8,
|
||||
"p95_ms": 970.5,
|
||||
"p99_ms": 970.5
|
||||
},
|
||||
"read_retries": 0,
|
||||
"worker_sample": {
|
||||
"cpu": "35.27%",
|
||||
"memory": "9.379MiB / 384MiB"
|
||||
},
|
||||
"submission_latency": {
|
||||
"p50_ms": 134.8,
|
||||
"p95_ms": 193.6,
|
||||
"p99_ms": 193.6
|
||||
},
|
||||
"verified_per_second": 6.76
|
||||
},
|
||||
"incident": {
|
||||
"queued": 8,
|
||||
"verified": 8,
|
||||
"lost_or_duplicate": 0,
|
||||
"submission_latency": {
|
||||
"p50_ms": 191.3,
|
||||
"p95_ms": 288.1,
|
||||
"p99_ms": 288.1
|
||||
},
|
||||
"ready_latency": {
|
||||
"p50_ms": 35133.3,
|
||||
"p95_ms": 35438.0,
|
||||
"p99_ms": 35438.0
|
||||
},
|
||||
"read_retries": 0,
|
||||
"rotation_seconds": 31.81,
|
||||
"worker_unavailable_seconds": 35.77,
|
||||
"drain_seconds_after_start": 1.33
|
||||
}
|
||||
},
|
||||
{
|
||||
"worker_image_id": "sha256:db4a3aab8e56b5ffc6352d1d35bcbcf242b38b05d711b26308277f67fc6af082",
|
||||
"baseline": {
|
||||
"jobs": 8,
|
||||
"verified": 8,
|
||||
"ready_latency": {
|
||||
"p50_ms": 688.9,
|
||||
"p95_ms": 988.6,
|
||||
"p99_ms": 988.6
|
||||
},
|
||||
"read_retries": 0,
|
||||
"worker_sample": {
|
||||
"cpu": "35.27%",
|
||||
"memory": "30.53MiB / 384MiB"
|
||||
},
|
||||
"submission_latency": {
|
||||
"p50_ms": 125.0,
|
||||
"p95_ms": 171.8,
|
||||
"p99_ms": 171.8
|
||||
},
|
||||
"verified_per_second": 6.67
|
||||
},
|
||||
"incident": {
|
||||
"queued": 8,
|
||||
"verified": 8,
|
||||
"lost_or_duplicate": 0,
|
||||
"submission_latency": {
|
||||
"p50_ms": 89.8,
|
||||
"p95_ms": 113.7,
|
||||
"p99_ms": 113.7
|
||||
},
|
||||
"ready_latency": {
|
||||
"p50_ms": 34903.0,
|
||||
"p95_ms": 35236.6,
|
||||
"p99_ms": 35236.6
|
||||
},
|
||||
"read_retries": 0,
|
||||
"rotation_seconds": 31.78,
|
||||
"worker_unavailable_seconds": 35.4,
|
||||
"drain_seconds_after_start": 1.26
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
PASS worker can consume queue; publish, foreign queue, sessions and FLUSHALL denied
|
||||
PASS PostgreSQL verified TLS; job read/processing update granted, business data/delete/DDL/plaintext denied.
|
||||
PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.
|
||||
PASS retired worker / broker: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS retired worker / Collector: SSLV3_ALERT_BAD_CERTIFICATE
|
||||
PASS renewed leaf, retired identity denied on three channels, old password rejected
|
||||
PASS PostgreSQL verified TLS; job read/processing update granted, business data/delete/DDL/plaintext denied.
|
||||
PASS PostgreSQL rejects the retired worker password.
|
||||
PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.
|
||||
PASS MinIO rejects the retired worker access key.
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"docker_platform": "linux/aarch64",
|
||||
"docker_vcpus": 2,
|
||||
"docker_memory_bytes": 2054832128,
|
||||
"fixture_png_bytes": 111817,
|
||||
"closed_loop_concurrency": 4,
|
||||
"queue_observation_seconds": 2,
|
||||
"runs": [
|
||||
{
|
||||
"worker_image_id": "sha256:db4a3aab8e56b5ffc6352d1d35bcbcf242b38b05d711b26308277f67fc6af082",
|
||||
"baseline": {
|
||||
"jobs": 8,
|
||||
"verified": 8,
|
||||
"ready_latency": {
|
||||
"p50_ms": 537.0,
|
||||
"p95_ms": 863.6,
|
||||
"p99_ms": 863.6
|
||||
},
|
||||
"read_retries": 0,
|
||||
"worker_sample": {
|
||||
"cpu": "33.60%",
|
||||
"memory": "19.06MiB / 384MiB"
|
||||
},
|
||||
"submission_latency": {
|
||||
"p50_ms": 89.2,
|
||||
"p95_ms": 107.8,
|
||||
"p99_ms": 107.8
|
||||
},
|
||||
"verified_per_second": 7.78
|
||||
},
|
||||
"incident": {
|
||||
"queued": 8,
|
||||
"verified": 8,
|
||||
"lost_or_duplicate": 0,
|
||||
"submission_latency": {
|
||||
"p50_ms": 64.8,
|
||||
"p95_ms": 87.3,
|
||||
"p99_ms": 87.3
|
||||
},
|
||||
"ready_latency": {
|
||||
"p50_ms": 34727.6,
|
||||
"p95_ms": 35094.8,
|
||||
"p99_ms": 35094.8
|
||||
},
|
||||
"read_retries": 0,
|
||||
"rotation_seconds": 31.68,
|
||||
"worker_unavailable_seconds": 35.22,
|
||||
"drain_seconds_after_start": 1.22
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
module gitflic.ru/akselbant/mtusi2026lab1-fork
|
||||
|
||||
go 1.26.4
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.9.0
|
||||
github.com/labstack/echo/v4 v4.16.1
|
||||
github.com/minio/minio-go/v7 v7.0.95
|
||||
github.com/redis/go-redis/v9 v9.12.1
|
||||
github.com/swaggest/swgui v1.8.9
|
||||
go.opentelemetry.io/otel v1.44.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.20.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.44.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0
|
||||
go.opentelemetry.io/otel/log v0.20.0
|
||||
go.opentelemetry.io/otel/metric v1.44.0
|
||||
go.opentelemetry.io/otel/sdk v1.44.0
|
||||
go.opentelemetry.io/otel/sdk/log v0.20.0
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0
|
||||
go.opentelemetry.io/otel/trace v1.44.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/sync v0.24.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.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.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.18.7 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.11 // indirect
|
||||
github.com/labstack/gommon v0.5.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.15 // indirect
|
||||
github.com/mattn/go-isatty v0.0.22 // 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
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
github.com/vearutop/statigz v1.4.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
|
||||
golang.org/x/net v0.62.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
|
||||
google.golang.org/grpc v1.83.2 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
@@ -0,0 +1,205 @@
|
||||
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
|
||||
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||
github.com/bool64/dev v0.2.45 h1:3nLKhAS/6Oklk3Mt2lHYSN/Cb4tdAD77KLwzeP+6eYE=
|
||||
github.com/bool64/dev v0.2.45/go.mod h1:iJbh1y/HkunEPhgebWRNcs8wfGq7sjvJ6W5iabL8ACg=
|
||||
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/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/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/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.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/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.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
|
||||
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.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
|
||||
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
|
||||
github.com/jackc/pgx/v5 v5.9.0 h1:T/dI+2TvmI2H8s/KH1/lXIbz1CUFk3gn5oTjr0/mBsE=
|
||||
github.com/jackc/pgx/v5 v5.9.0/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.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
|
||||
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
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/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
|
||||
github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ=
|
||||
github.com/labstack/echo/v4 v4.16.1 h1:h05NuF1GvNu6jSAZxOv++AdjD/NJK+mZdGy0thiiuns=
|
||||
github.com/labstack/echo/v4 v4.16.1/go.mod h1:V/EQaTVHYJH92QhbQe7kFQ4mjgcjxLQQUQtAN87zZdw=
|
||||
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
||||
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
|
||||
github.com/labstack/gommon v0.5.0 h1:6VSQ2NOzsnEJ5W6+84E0RbcaDDmgB6NIAzWCczTEe6c=
|
||||
github.com/labstack/gommon v0.5.0/go.mod h1:Rzlg7HHy1maLfzBYGg9NZcVuz1sA68HHhLjhcEllYE0=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY=
|
||||
github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
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 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
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.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/swaggest/swgui v1.8.9 h1:cxAgIwouPpZPlvX68jY5fpwarzLbkc8/IL6DMj+H460=
|
||||
github.com/swaggest/swgui v1.8.9/go.mod h1:eTJfgwudbyw9xMwqO26vs82ei2u6//JnUAofx2vGB3M=
|
||||
github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww=
|
||||
github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||
github.com/vearutop/statigz v1.4.0 h1:RQL0KG3j/uyA/PFpHeZ/L6l2ta920/MxlOAIGEOuwmU=
|
||||
github.com/vearutop/statigz v1.4.0/go.mod h1:LYTolBLiz9oJISwiVKnOQoIwhO1LWX1A7OECawGS8XE=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
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/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
|
||||
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
|
||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.14.0 h1:QQqYw3lkrzwVsoEX0w//EhH/TCnpRdEenKBOOEIMjWc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.14.0/go.mod h1:gSVQcr17jk2ig4jqJ2DX30IdWH251JcNAecvrqTxH1s=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.20.0 h1:owlhcJ3QO3X0YTDTCcDZ4V+6aVDkWbNmBoQ5NUp7Oww=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.20.0/go.mod h1:MP4eemTiI9zC8fgg+DYynhYDYf3ba72S376TvP+Ye0Q=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.38.0 h1:Oe2z/BCg5q7k4iXC3cqJxKYg0ieRiOqF0cecFYdPTwk=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.38.0/go.mod h1:ZQM5lAJpOsKnYagGg/zV2krVqTtaVdYdDkhMoX6Oalg=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.44.0 h1:RuynHbfU8JUEw7DyONgkVYg2SVtsoF28y0LGIr69jgA=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.44.0/go.mod h1:qZF+/lBs71APw8mlnEZcqZHMzqrYrsFiJOv83lX1OGo=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 h1:aTL7F04bJHUlztTsNGJ2l+6he8c+y/b//eR0jjjemT4=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0/go.mod h1:kldtb7jDTeol0l3ewcmd8SDvx3EmIE7lyvqbasU3QC4=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 h1:lgh3PiVrRUWMLOVSkQicxzZll5NjF1r+AtsX1XRIHw0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0/go.mod h1:5Cnhth3m/AgOeTgE3ex12pPmiu/gGtZit03kSzx9X7s=
|
||||
go.opentelemetry.io/otel/log v0.14.0 h1:2rzJ+pOAZ8qmZ3DDHg73NEKzSZkhkGIua9gXtxNGgrM=
|
||||
go.opentelemetry.io/otel/log v0.14.0/go.mod h1:5jRG92fEAgx0SU/vFPxmJvhIuDU9E1SUnEQrMlJpOno=
|
||||
go.opentelemetry.io/otel/log v0.20.0 h1:/5i0vuHxCLWUfChWG41K9wkM0jafruPw9NU1/RCJirs=
|
||||
go.opentelemetry.io/otel/log v0.20.0/go.mod h1:wOcMcjsZpG8x7Bak7IhSi/lg8wscV2C1VdrKCLPlt0E=
|
||||
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
|
||||
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
|
||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
||||
go.opentelemetry.io/otel/sdk/log v0.14.0 h1:JU/U3O7N6fsAXj0+CXz21Czg532dW2V4gG1HE/e8Zrg=
|
||||
go.opentelemetry.io/otel/sdk/log v0.14.0/go.mod h1:imQvII+0ZylXfKU7/wtOND8Hn4OpT3YUoIgqJVksUkM=
|
||||
go.opentelemetry.io/otel/sdk/log v0.20.0 h1:vM3xI7TQgKPiSghe6urZtAkyFY7SodrSpC83CffDFuY=
|
||||
go.opentelemetry.io/otel/sdk/log v0.20.0/go.mod h1:Knej2nmsTUzN79T2eeXdRsjjPcoxoq2pUyUHz9TFyyU=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.14.0 h1:Ijbtz+JKXl8T2MngiwqBlPaHqc4YCaP/i13Qrow6gAM=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.14.0/go.mod h1:dCU8aEL6q+L9cYTqcVOk8rM9Tp8WdnHOPLiBgp0SGOA=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.20.0 h1:OqdRZ1guyzamK3M6LlRsmGqRrjkHWw6WZOKKli5ELpg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
|
||||
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
|
||||
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
|
||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4=
|
||||
go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE=
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
|
||||
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
|
||||
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
|
||||
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
|
||||
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
|
||||
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 h1:BIRfGDEjiHRrk0QKZe3Xv2ieMhtgRGeLcZQ0mIVn4EY=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5/go.mod h1:j3QtIyytwqGr1JUDtYXwtMXWPKsEa5LtzIFN1Wn5WvE=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 h1:eaY8u2EuxbRv7c3NiGK0/NedzVsCcV6hDuU5qPX5EGE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5/go.mod h1:M4/wBTSeyLxupu3W3tJtOgB14jILAS/XWPSSa3TAlJc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.75.0 h1:+TW+dqTd2Biwe6KKfhE5JpiYIBWq865PhKGSXiivqt4=
|
||||
google.golang.org/grpc v1.75.0/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ=
|
||||
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.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
|
||||
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/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=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
+3
-5
@@ -1,7 +1,5 @@
|
||||
# Инфраструктура студента
|
||||
# Настройки стенда
|
||||
|
||||
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
|
||||
Compose запускает две реплики API, HAProxy, worker, PostgreSQL, Redis, MinIO, OpenBao и подсистему телеметрии. Goose применяет миграции из lab6. Операторские контейнеры выдают рабочие права и проверяют сервисы.
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
Операторские команды создают сертификаты и секреты перед запуском. CA и ключи остаются на хосте. Опубликованные порты относятся к входному HTTPS, Grafana и OpenBao. [Запуск](../REPORT.md) · [Матрица доверия](../contracts/trust-matrix.md)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
export PGPASSWORD="$(cat /bootstrap/admin/POSTGRES_PASSWORD)"
|
||||
if [ "${1:-}" = worker ]; then
|
||||
exec psql -X -q -h postgres -U messenger -d messenger -f /rotate-worker.sql
|
||||
fi
|
||||
exec psql -X -q -h postgres -U messenger -d messenger -f /grants.sql
|
||||
@@ -0,0 +1,32 @@
|
||||
\set ON_ERROR_STOP on
|
||||
SELECT 'CREATE ROLE messenger_api LOGIN' WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='messenger_api') \gexec
|
||||
SELECT 'CREATE ROLE messenger_worker LOGIN' WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='messenger_worker') \gexec
|
||||
SELECT 'CREATE ROLE messenger_operator LOGIN' WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='messenger_operator') \gexec
|
||||
\set api_password `cat /bootstrap/api/POSTGRES_PASSWORD`
|
||||
\set worker_password `cat /bootstrap/worker/POSTGRES_PASSWORD`
|
||||
\set operator_password `cat /bootstrap/operator/POSTGRES_PASSWORD`
|
||||
ALTER ROLE messenger_api PASSWORD :'api_password';
|
||||
ALTER ROLE messenger_worker PASSWORD :'worker_password';
|
||||
ALTER ROLE messenger_operator PASSWORD :'operator_password';
|
||||
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
|
||||
REVOKE ALL ON SCHEMA public FROM PUBLIC;
|
||||
GRANT CONNECT ON DATABASE messenger TO messenger_api, messenger_worker, messenger_operator;
|
||||
GRANT USAGE ON SCHEMA public TO messenger_api, messenger_worker, messenger_operator;
|
||||
GRANT SELECT, INSERT ON users, chats, chat_members, messages TO messenger_api;
|
||||
GRANT UPDATE (password_hash) ON users TO messenger_api;
|
||||
GRANT SELECT, INSERT, UPDATE ON attachments, attachment_jobs, attachment_outbox TO messenger_api;
|
||||
REVOKE ALL ON attachments, attachment_jobs, attachment_outbox FROM messenger_worker;
|
||||
GRANT SELECT (id, status, object_key, content_type, size_bytes, variants, pipeline_version,
|
||||
staging_key, sha256, width, height, updated_at, storage_cleaned_at)
|
||||
ON attachments TO messenger_worker;
|
||||
GRANT SELECT (id, attachment_id, state, attempts, max_attempts, available_at, pipeline_version,
|
||||
fence, lease_until, last_error, updated_at)
|
||||
ON attachment_jobs TO messenger_worker;
|
||||
GRANT SELECT (job_id) ON attachment_outbox TO messenger_worker;
|
||||
GRANT SELECT ON attachments, attachment_jobs, attachment_outbox TO messenger_operator;
|
||||
GRANT SELECT (attachment_ids) ON messages TO messenger_operator;
|
||||
GRANT UPDATE (status, updated_at, error_code, variants, staging_key, storage_cleaned_at) ON attachments TO messenger_worker;
|
||||
GRANT UPDATE (state, attempts, fence, lease_until, available_at, last_error, updated_at) ON attachment_jobs TO messenger_worker;
|
||||
GRANT UPDATE (published_at, available_at) ON attachment_outbox TO messenger_worker;
|
||||
GRANT UPDATE ON attachments, attachment_jobs, attachment_outbox TO messenger_operator;
|
||||
GRANT INSERT ON attachment_replays TO messenger_operator;
|
||||
@@ -0,0 +1,519 @@
|
||||
{
|
||||
"uid": "messenger",
|
||||
"title": "Messenger observability",
|
||||
"schemaVersion": 41,
|
||||
"version": 1,
|
||||
"refresh": "5s",
|
||||
"time": {
|
||||
"from": "now-15m",
|
||||
"to": "now"
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "API RPS (business routes)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(rate(messenger_http_requests_total[$__rate_interval])) by (route)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "API 5xx / all business requests",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "(sum(rate(messenger_http_requests_total{status_class=\"5xx\"}[$__rate_interval])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total[$__rate_interval])),0.001)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "API p50 / p95 / p99 (all replicas, histogram)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "histogram_quantile(0.5,sum(rate(messenger_http_duration_seconds_bucket[$__rate_interval])) by(le))",
|
||||
"legendFormat": "p50",
|
||||
"refId": "A"
|
||||
},
|
||||
{
|
||||
"expr": "histogram_quantile(0.95,sum(rate(messenger_http_duration_seconds_bucket[$__rate_interval])) by(le))",
|
||||
"legendFormat": "p95",
|
||||
"refId": "B"
|
||||
},
|
||||
{
|
||||
"expr": "histogram_quantile(0.99,sum(rate(messenger_http_duration_seconds_bucket[$__rate_interval])) by(le))",
|
||||
"legendFormat": "p99",
|
||||
"refId": "C"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "Worker job outcomes per second",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(rate(messenger_jobs_total[$__rate_interval])) by(outcome)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Worker job p95 duration",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "histogram_quantile(0.95,sum(rate(messenger_job_duration_seconds_bucket[$__rate_interval])) by(le,outcome))",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Time from durable acceptance to ready p95",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "histogram_quantile(0.95,sum(rate(messenger_attachment_ready_seconds_bucket[$__rate_interval])) by(le))",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "Authoritative queue depth (max across observers)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "max(messenger_queue_depth)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "Oldest unfinished job age",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "max(messenger_queue_oldest_age_seconds)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "DB pool acquired / acquiring / max",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "messenger_db_pool_used",
|
||||
"legendFormat": "used {{service_name}} {{service_instance_id}}",
|
||||
"refId": "A"
|
||||
},
|
||||
{
|
||||
"expr": "messenger_db_pool_waiting",
|
||||
"legendFormat": "waiting {{service_name}} {{service_instance_id}}",
|
||||
"refId": "B"
|
||||
},
|
||||
{
|
||||
"expr": "messenger_db_pool_max",
|
||||
"legendFormat": "max {{service_name}} {{service_instance_id}}",
|
||||
"refId": "C"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"title": "Worker saturation busy / capacity",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(messenger_worker_busy{service_name=\"messenger-worker\"}) / clamp_min(sum(messenger_worker_capacity{service_name=\"messenger-worker\"}),1)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"title": "Go runtime reserved memory (MemStats.Sys)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 40,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "messenger_process_memory_bytes",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"title": "Process CPU seconds / second",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 40,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "rate(messenger_process_cpu_seconds_total[$__rate_interval])",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"title": "SDK failed telemetry export operations",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 48,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "messenger_telemetry_export_errors",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"title": "Exporter failed spans (attempts, not unique loss)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 48,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(otelcol_exporter_send_failed_spans_total) by (exporter)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 99,
|
||||
"title": "API and worker structured logs; trace ID opens Tempo",
|
||||
"type": "logs",
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 56,
|
||||
"w": 24,
|
||||
"h": 10
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "{service_name=~\"messenger-api|messenger-worker\"} | json",
|
||||
"refId": "A"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"annotations": {
|
||||
"list": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: Messenger
|
||||
type: file
|
||||
options: {path: /var/lib/grafana/dashboards}
|
||||
updateIntervalSeconds: 10
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"apiVersion": 1,
|
||||
"datasources": [
|
||||
{
|
||||
"name": "Prometheus",
|
||||
"uid": "prometheus",
|
||||
"type": "prometheus",
|
||||
"access": "proxy",
|
||||
"url": "https://prometheus:49090",
|
||||
"isDefault": true,
|
||||
"jsonData": {}
|
||||
},
|
||||
{
|
||||
"name": "Loki",
|
||||
"uid": "loki",
|
||||
"type": "loki",
|
||||
"access": "proxy",
|
||||
"url": "https://loki:43101",
|
||||
"jsonData": {
|
||||
"derivedFields": [{
|
||||
"name": "TraceID",
|
||||
"matcherRegex": "\"trace_id\":\"([a-f0-9]{32})\"",
|
||||
"datasourceUid": "tempo",
|
||||
"url": "$${__value.raw}"
|
||||
}]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Tempo",
|
||||
"uid": "tempo",
|
||||
"type": "tempo",
|
||||
"access": "proxy",
|
||||
"url": "https://tempo:43200",
|
||||
"jsonData": {
|
||||
"tracesToLogsV2": {"datasourceUid": "loki", "filterByTraceID": true},
|
||||
"serviceMap": {"datasourceUid": "prometheus"}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 1024
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2 no-tls-tickets
|
||||
|
||||
defaults
|
||||
log global
|
||||
mode http
|
||||
timeout connect 1s
|
||||
timeout client 55s
|
||||
timeout server 55s
|
||||
timeout check 1s
|
||||
retries 0
|
||||
option http-server-close
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 1s
|
||||
hold obsolete 1s
|
||||
hold nx 1s
|
||||
hold refused 1s
|
||||
hold timeout 1s
|
||||
|
||||
frontend public
|
||||
bind :8443 ssl crt /identity/server.pem
|
||||
unique-id-format %[uuid()]
|
||||
acl oversized req.hdr_val(content-length) gt 10485760
|
||||
http-request return status 413 content-type application/json lf-string '{"error":{"code":"payload_too_large","message":"Payload exceeds 10 MiB","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr X-Instance-Id gateway if oversized
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
|
||||
http-check expect status 200
|
||||
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 1
|
||||
server-template replica 1-8 api:8080 ssl verify required ca-file /trust/ca.crt verifyhost api sni str(api) crt /identity/client.pem check check-sni api resolvers docker init-addr none
|
||||
@@ -0,0 +1,27 @@
|
||||
auth_enabled: false
|
||||
server: {http_listen_address: 127.0.0.1, http_listen_port: 3100, grpc_listen_address: 127.0.0.1, grpc_listen_port: 9096}
|
||||
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-04-01'
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index: {prefix: index_, period: 24h}
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
retention_period: 168h
|
||||
ingestion_rate_mb: 4
|
||||
ingestion_burst_size_mb: 8
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
analytics: {reporting_enabled: false}
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Keep the password out of argv and disable automatic dotenv loading.
|
||||
if [ -n "${POSTGRES_PASSWORD_FILE:-}" ]; then
|
||||
PGPASSWORD=$(cat "$POSTGRES_PASSWORD_FILE")
|
||||
export PGPASSWORD
|
||||
fi
|
||||
exec goose -env /dev/null -dir /migrations -timeout 30s "$@"
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
export MINIO_ROOT_USER="$(cat /bootstrap/S3_ACCESS_KEY)"
|
||||
export MINIO_ROOT_PASSWORD="$(cat /bootstrap/S3_SECRET_KEY)"
|
||||
exec minio server /data --certs-dir /identity --address :9000 --console-address 127.0.0.1:9001
|
||||
@@ -1,7 +1,9 @@
|
||||
# OpenBao — реализовать конфигурацию и политики
|
||||
# OpenBao
|
||||
|
||||
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
|
||||
Контейнер запускает `bao server -config=/etc/bao.hcl` и использует том `openbao_data`. Декларативный аудит пишет JSONL в том. OpenBao хэширует чувствительные поля журнала. Приложения используют TLS, проверяют имя `openbao` и входят по сертификату.
|
||||
|
||||
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
|
||||
`scripts/stand.py bootstrap` создаёт схему Shamir 2 из 3 и сохраняет ответ в каталоге оператора. Каталог оператора доступен с хоста и отсутствует в mount контейнеров. В учебном стенде один оператор хранит все доли. Для своего окружения разнесите доли между операторами и сохраните резервную копию отдельно.
|
||||
|
||||
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
|
||||
После перезапуска выполните `python3 scripts/stand.py unseal`. Пароли сервисов остаются в KV v2. OpenBao проверяет конкретный сертификат, привязанный к роли. Для продления доступа сервис входит повторно через 10 секунд. Если смените сертификат, обновите привязку и перезапустите сервис. Для worker эту процедуру выполняет `rotate-worker`. [Операторские команды](../../REPORT.md)
|
||||
|
||||
`disable_mlock` позволяет контейнеру работать без `IPC_LOCK`. Это учебное ограничение. OpenBao использует один том и один локальный журнал. [Официальная документация по аудиту](https://openbao.org/docs/audit/)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
path "lab/data/api" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
path "auth/token/revoke-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
ui = false
|
||||
disable_mlock = true
|
||||
api_addr = "https://openbao:8200"
|
||||
storage "file" {
|
||||
path = "/openbao/file"
|
||||
}
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
tls_cert_file = "/identity/tls.crt"
|
||||
tls_key_file = "/identity/tls.key"
|
||||
tls_client_ca_file = "/trust/ca.crt"
|
||||
tls_min_version = "tls12"
|
||||
}
|
||||
audit "file" "operator-audit" {
|
||||
options {
|
||||
file_path = "/openbao/file/audit.jsonl"
|
||||
log_raw = "false"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
path "lab/data/operator" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
path "auth/token/revoke-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
path "lab/data/worker" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
path "auth/token/revoke-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
# Конфигурация наблюдаемости — реализовать
|
||||
# Сбор телеметрии
|
||||
|
||||
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
|
||||
API и worker передают OTLP/HTTP через mTLS на Collector. Collector отправляет логи в Loki и трассы в Tempo. Prometheus собирает метрики раз в 5 секунд. Grafana получает данные через HTTPS с сертификатом роли `grafana`.
|
||||
|
||||
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
|
||||
Настройки прокси задают разрешённые URI SAN и операции HTTP. Collector, Loki, Tempo и Prometheus слушают открытый протокол только внутри своих сетевых пространств имён. [Матрица доверия](../../contracts/trust-matrix.md)
|
||||
|
||||
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
|
||||
В момент запуска оператор создаёт локальные настройки источников Grafana из шаблонов. Настройки содержат приватный ключ Grafana. Панели и настройки сбора входят в репозиторий. Grafana доступна по HTTPS на порту 13000. [Запуск и проверка](../../REPORT.md)
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http: {endpoint: '127.0.0.1:4318'}
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 128
|
||||
spike_limit_mib: 32
|
||||
batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 256
|
||||
send_batch_max_size: 512
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 127.0.0.1:8889
|
||||
metric_expiration: 15s
|
||||
resource_to_telemetry_conversion: {enabled: true}
|
||||
otlphttp/tempo:
|
||||
endpoint: https://tempo:44318
|
||||
tls: {ca_file: /trust/ca.crt, cert_file: /identity/tls.crt, key_file: /identity/tls.key}
|
||||
timeout: 2s
|
||||
sending_queue: {enabled: true, queue_size: 256, num_consumers: 2}
|
||||
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 5s, max_elapsed_time: 20s}
|
||||
otlphttp/loki:
|
||||
endpoint: https://loki:43100/otlp
|
||||
tls: {ca_file: /trust/ca.crt, cert_file: /identity/tls.crt, key_file: /identity/tls.key}
|
||||
timeout: 2s
|
||||
sending_queue: {enabled: true, queue_size: 256, num_consumers: 2}
|
||||
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 5s, max_elapsed_time: 20s}
|
||||
service:
|
||||
telemetry:
|
||||
metrics:
|
||||
level: detailed
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus: {host: 127.0.0.1, port: 8888}
|
||||
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]}
|
||||
@@ -0,0 +1,2 @@
|
||||
local all all peer map=bootstrap
|
||||
hostssl all all all scram-sha-256
|
||||
@@ -0,0 +1 @@
|
||||
bootstrap postgres messenger
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
install -m 600 /identity/tls.key /tmp/postgres.key
|
||||
exec docker-entrypoint.sh postgres -c ssl=on \
|
||||
-c ssl_cert_file=/identity/tls.crt -c ssl_key_file=/tmp/postgres.key \
|
||||
-c ident_file=/etc/pg_ident.conf -c hba_file=/etc/pg_hba.conf -c shared_buffers=32MB -c max_connections=48
|
||||
@@ -0,0 +1,19 @@
|
||||
groups:
|
||||
- name: messenger-slo
|
||||
rules:
|
||||
- alert: APIHighErrorRate
|
||||
expr: sum(rate(messenger_http_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total[1m])), 0.01) > 0.05
|
||||
for: 5s
|
||||
labels: {severity: warning}
|
||||
annotations:
|
||||
summary: More than 5 percent API server failures over 1 minute
|
||||
runbook_url: http://localhost:13000/d/messenger/messenger-observability
|
||||
description: Excludes health and client 4xx. Inspect PostgreSQL spans and pool; see RUNBOOK.md.
|
||||
- alert: QueueLagGrowing
|
||||
expr: max(messenger_queue_oldest_age_seconds) > 10 and max(messenger_queue_depth) > 0
|
||||
for: 5s
|
||||
labels: {severity: warning}
|
||||
annotations:
|
||||
summary: Oldest unfinished attachment exceeds 10 seconds
|
||||
runbook_url: http://localhost:13000/d/messenger/messenger-observability
|
||||
description: Inspect worker capacity, busy, outcomes and dependency spans; see RUNBOOK.md.
|
||||
@@ -0,0 +1,26 @@
|
||||
global:
|
||||
scrape_interval: 5s
|
||||
evaluation_interval: 5s
|
||||
rule_files: [/etc/prometheus/alerts.yaml]
|
||||
scrape_configs:
|
||||
- job_name: messenger
|
||||
scheme: https
|
||||
tls_config: &client
|
||||
ca_file: /trust/ca.crt
|
||||
cert_file: /identity/tls.crt
|
||||
key_file: /identity/tls.key
|
||||
static_configs: [{targets: ['collector:48889']}]
|
||||
- job_name: collector
|
||||
scheme: https
|
||||
tls_config: *client
|
||||
static_configs: [{targets: ['collector:48888']}]
|
||||
- job_name: tempo
|
||||
scheme: https
|
||||
tls_config: *client
|
||||
static_configs: [{targets: ['tempo:43201']}]
|
||||
- job_name: loki
|
||||
scheme: https
|
||||
tls_config: *client
|
||||
static_configs: [{targets: ['loki:43102']}]
|
||||
- job_name: prometheus
|
||||
static_configs: [{targets: ['localhost:9090']}]
|
||||
@@ -0,0 +1,10 @@
|
||||
bind 127.0.0.1
|
||||
protected-mode yes
|
||||
port 6379
|
||||
dir /data
|
||||
aclfile /acl/users.acl
|
||||
appendonly yes
|
||||
appendfsync always
|
||||
save ""
|
||||
maxmemory 96mb
|
||||
maxmemory-policy noeviction
|
||||
@@ -0,0 +1,6 @@
|
||||
\set ON_ERROR_STOP on
|
||||
\set worker_password `cat /bootstrap/worker/POSTGRES_PASSWORD`
|
||||
ALTER ROLE messenger_worker PASSWORD :'worker_password';
|
||||
SELECT count(*) FROM (
|
||||
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='messenger_worker'
|
||||
) AS terminated;
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect":"Allow","Action":["s3:GetBucketLocation"],"Resource":["arn:aws:s3:::attachments"]},
|
||||
{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::attachments"],"Condition":{"StringLike":{"s3:prefix":["original/*"]}}},
|
||||
{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::attachments/original/*"]},
|
||||
{"Effect":"Allow","Action":["s3:PutObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::attachments/staging/*"]}
|
||||
]
|
||||
}
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
export MC_CONFIG_DIR=/tmp/mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /trust/ca.crt "$MC_CONFIG_DIR/certs/CAs/lab.crt"
|
||||
mc alias set admin https://minio:9000 "$(cat /bootstrap/admin/S3_ACCESS_KEY)" "$(cat /bootstrap/admin/S3_SECRET_KEY)" >/dev/null
|
||||
mc ready admin >/dev/null
|
||||
mc mb --ignore-existing admin/attachments >/dev/null
|
||||
mc anonymous set none admin/attachments >/dev/null
|
||||
if [ "${1:-}" = worker ]; then
|
||||
old=$(cat /retired/S3_ACCESS_KEY)
|
||||
mc admin user rm admin "$old" >/dev/null
|
||||
set -- worker
|
||||
else
|
||||
set -- api worker operator
|
||||
fi
|
||||
for role do
|
||||
mc admin policy create admin "attachments-$role" "/policies/s3-$role.json" >/dev/null
|
||||
key=$(cat "/bootstrap/$role/S3_ACCESS_KEY")
|
||||
mc admin user add admin "$key" "$(cat "/bootstrap/$role/S3_SECRET_KEY")" >/dev/null
|
||||
mc admin policy attach admin "attachments-$role" --user "$key" >/dev/null
|
||||
done
|
||||
printf '%s\n' 'Private bucket and scoped S3 accounts configured.'
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetBucketLocation"],
|
||||
"Resource": ["arn:aws:s3:::attachments"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::attachments"],
|
||||
"Condition": {"StringLike": {"s3:prefix": ["original/*", "staging/*"]}}
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::attachments/original/*", "arn:aws:s3:::attachments/staging/*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect":"Allow","Action":["s3:GetBucketLocation"],"Resource":["arn:aws:s3:::attachments"]},
|
||||
{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::attachments"],"Condition":{"StringLike":{"s3:prefix":["staging/*"]}}},
|
||||
{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::attachments/staging/*"]},
|
||||
{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::attachments/original/*"]}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
server: {http_listen_address: 127.0.0.1, http_listen_port: 3200, grpc_listen_address: 127.0.0.1}
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http: {endpoint: '127.0.0.1:4318'}
|
||||
ingester:
|
||||
max_block_duration: 1m
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
max_compaction_objects: 20000
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal: {path: /var/tempo/wal}
|
||||
local: {path: /var/tempo/blocks}
|
||||
usage_report: {reporting_enabled: false}
|
||||
@@ -0,0 +1,31 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) authorizedChat(c echo.Context, requestedChat domain.Chat) (domain.Chat, bool, error) {
|
||||
chat, err := h.useCase.GetChat(c.Request().Context(), authenticatedUser(c).ID, requestedChat)
|
||||
if err != nil {
|
||||
return domain.Chat{}, false, h.useCaseError(c, err)
|
||||
}
|
||||
return chat, true, nil
|
||||
}
|
||||
|
||||
func (h *Chat) cursorPosition(raw string, present bool, scope, owner string) (*domain.Position, error) {
|
||||
if !present {
|
||||
return nil, nil
|
||||
}
|
||||
if raw == "" {
|
||||
return nil, errors.New("empty cursor")
|
||||
}
|
||||
createdAt, id, err := h.cursor.decode(raw, scope, owner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &domain.Position{CreatedAt: createdAt, ID: id}, nil
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mime"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func (h *Chat) WithAttachments(service *attachment.Service) *Chat { h.attachments = service; return h }
|
||||
func (h *Chat) uploadAttachment(c echo.Context) error {
|
||||
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: c.Param("chat_id")})
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
filename, present, err := oneQueryValue(c, "filename")
|
||||
if err != nil || !present {
|
||||
return h.invalid(c, "Требуется один filename")
|
||||
}
|
||||
if c.Request().ContentLength > attachment.MaxBytes {
|
||||
return h.writeError(c, 413, "payload_too_large", "Файл превышает 10 MiB")
|
||||
}
|
||||
// Both socket reads and the application operation have a fixed deadline.
|
||||
deadline := time.Now().Add(attachment.UploadTimeout)
|
||||
_ = http.NewResponseController(c.Response().Writer).SetReadDeadline(deadline)
|
||||
defer http.NewResponseController(c.Response().Writer).SetReadDeadline(time.Time{})
|
||||
c.Request().Body = http.MaxBytesReader(c.Response(), c.Request().Body, attachment.MaxBytes+1)
|
||||
a, err := h.attachments.Upload(c.Request().Context(), chat.ID, authenticatedUser(c).ID, filename, c.Request().Header.Get("Content-Type"), c.Request().Body)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusAccepted, a)
|
||||
}
|
||||
func (h *Chat) getAttachment(c echo.Context) error {
|
||||
a, err := h.attachments.Get(c.Request().Context(), c.Param("attachment_id"), authenticatedUser(c).ID)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, a)
|
||||
}
|
||||
func (h *Chat) attachmentContent(c echo.Context) error {
|
||||
a, err := h.attachments.Get(c.Request().Context(), c.Param("attachment_id"), authenticatedUser(c).ID)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
variant, present, err := oneQueryValue(c, "variant")
|
||||
if err != nil {
|
||||
return h.invalid(c, "Некорректный variant")
|
||||
}
|
||||
if a.Status != "ready" {
|
||||
return h.writeError(c, 409, "conflict", "Вложение не готово")
|
||||
}
|
||||
if !present {
|
||||
variant = "original"
|
||||
}
|
||||
a, err = h.attachments.Variant(a, variant)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(c.Request().Context(), 45*time.Second)
|
||||
defer cancel()
|
||||
obj, err := h.attachments.Content(ctx, a)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
defer obj.Close()
|
||||
c.Response().Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
|
||||
c.Response().Header().Set("X-Content-Type-Options", "nosniff")
|
||||
c.Response().Header().Set("Cache-Control", "private, no-store")
|
||||
return c.Stream(http.StatusOK, a.ContentType, obj)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) createChat(c echo.Context) error {
|
||||
var request dto.CreateChatRequest
|
||||
if err := decodeJSON(c, &request); err != nil {
|
||||
return h.jsonError(c, err)
|
||||
}
|
||||
callerID := authenticatedUser(c).ID
|
||||
chat, err := h.useCase.CreateChat(c.Request().Context(), callerID, createChatRequestToDomain(request))
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, createChatResponseFromDomain(chat))
|
||||
}
|
||||
|
||||
func createChatRequestToDomain(request dto.CreateChatRequest) domain.Chat {
|
||||
return domain.Chat{Title: request.Title, MemberIDs: request.MemberIDs}
|
||||
}
|
||||
|
||||
func createChatResponseFromDomain(chat domain.Chat) dto.CreateChatResponse {
|
||||
return dto.CreateChatResponse{
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (h *Chat) createMessage(c echo.Context) error {
|
||||
request := dto.CreateMessageRequest{ChatID: c.Param("chat_id")}
|
||||
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: request.ChatID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if err := decodeJSON(c, &request); err != nil {
|
||||
return h.jsonError(c, err)
|
||||
}
|
||||
request.ChatID = chat.ID
|
||||
|
||||
keys := c.Request().Header.Values("Idempotency-Key")
|
||||
if len(keys) != 1 || !idempotencyKeyPattern.MatchString(keys[0]) {
|
||||
return h.invalid(c, "Требуется Idempotency-Key: ASCII [A-Za-z0-9._:-]{1,128}")
|
||||
}
|
||||
input := createMessageRequestToDomain(request)
|
||||
input.IdempotencyKey = keys[0]
|
||||
message, err := h.useCase.CreateMessage(c.Request().Context(), authenticatedUser(c).ID, input)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, createMessageResponseFromDomain(message))
|
||||
}
|
||||
|
||||
func createMessageRequestToDomain(request dto.CreateMessageRequest) domain.Message {
|
||||
return domain.Message{ChatID: request.ChatID, Text: request.Text, AttachmentIDs: request.AttachmentIDs}
|
||||
}
|
||||
|
||||
func createMessageResponseFromDomain(message domain.Message) dto.CreateMessageResponse {
|
||||
return dto.CreateMessageResponse{
|
||||
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||
Text: message.Text, AttachmentIDs: nonnilIDs(message.AttachmentIDs), CreatedAt: dto.Timestamp(message.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func nonnilIDs(ids []string) []string {
|
||||
if ids == nil {
|
||||
return []string{}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) createUser(c echo.Context) error {
|
||||
var request dto.CreateUserRequest
|
||||
if err := decodeJSON(c, &request); err != nil {
|
||||
return h.jsonError(c, err)
|
||||
}
|
||||
user, err := h.useCase.CreateUser(c.Request().Context(), createUserRequestToDomain(request), request.Password)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, createUserResponseFromDomain(user))
|
||||
}
|
||||
|
||||
func createUserRequestToDomain(request dto.CreateUserRequest) domain.User {
|
||||
return domain.User{Username: request.Username, DisplayName: request.DisplayName}
|
||||
}
|
||||
|
||||
func createUserResponseFromDomain(user domain.User) dto.CreateUserResponse {
|
||||
return dto.CreateUserResponse{
|
||||
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) currentUser(c echo.Context) error {
|
||||
user := authenticatedUser(c)
|
||||
return c.JSON(http.StatusOK, currentUserResponseFromDomain(user))
|
||||
}
|
||||
|
||||
func currentUserResponseFromDomain(user domain.User) dto.CurrentUserResponse {
|
||||
return dto.CurrentUserResponse{
|
||||
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type cursorPayload struct {
|
||||
Scope string `json:"scope"`
|
||||
Owner string `json:"owner"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type cursorCodec struct {
|
||||
secret [32]byte
|
||||
}
|
||||
|
||||
func (c cursorCodec) encode(scope, owner string, createdAt time.Time, id string) string {
|
||||
payload, err := json.Marshal(cursorPayload{
|
||||
Scope: scope,
|
||||
Owner: owner,
|
||||
CreatedAt: createdAt.UTC().Format(time.RFC3339Nano),
|
||||
ID: id,
|
||||
})
|
||||
if err != nil {
|
||||
panic("cannot encode cursor: " + err.Error())
|
||||
}
|
||||
signature := c.sign(payload)
|
||||
return base64.RawURLEncoding.EncodeToString(payload) + "." + base64.RawURLEncoding.EncodeToString(signature)
|
||||
}
|
||||
|
||||
func (c cursorCodec) decode(raw, scope, owner string) (time.Time, string, error) {
|
||||
parts := strings.Split(raw, ".")
|
||||
if len(parts) != 2 {
|
||||
return time.Time{}, "", errors.New("malformed cursor")
|
||||
}
|
||||
payload, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||
if err != nil {
|
||||
return time.Time{}, "", errors.New("malformed cursor")
|
||||
}
|
||||
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil || !hmac.Equal(signature, c.sign(payload)) {
|
||||
return time.Time{}, "", errors.New("invalid cursor signature")
|
||||
}
|
||||
var value cursorPayload
|
||||
if err := json.Unmarshal(payload, &value); err != nil {
|
||||
return time.Time{}, "", errors.New("malformed cursor payload")
|
||||
}
|
||||
if value.Scope != scope || value.Owner != owner {
|
||||
return time.Time{}, "", errors.New("cursor belongs to another resource")
|
||||
}
|
||||
parsedID, err := uuid.Parse(value.ID)
|
||||
if err != nil || parsedID.String() != value.ID {
|
||||
return time.Time{}, "", errors.New("malformed cursor id")
|
||||
}
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, value.CreatedAt)
|
||||
if err != nil {
|
||||
return time.Time{}, "", errors.New("malformed cursor timestamp")
|
||||
}
|
||||
return createdAt, value.ID, nil
|
||||
}
|
||||
|
||||
func (c cursorCodec) sign(payload []byte) []byte {
|
||||
mac := hmac.New(sha256.New, c.secret[:])
|
||||
_, _ = mac.Write(payload)
|
||||
return mac.Sum(nil)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) invalid(c echo.Context, message string) error {
|
||||
return h.writeError(c, http.StatusBadRequest, "invalid_request", message)
|
||||
}
|
||||
|
||||
func (h *Chat) jsonError(c echo.Context, err error) error {
|
||||
if errors.Is(err, errUnsupportedMediaType) {
|
||||
return h.writeError(c, http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type должен быть application/json")
|
||||
}
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
return h.writeError(c, http.StatusRequestEntityTooLarge, "payload_too_large", "Тело запроса слишком большое")
|
||||
}
|
||||
return h.invalid(c, err.Error())
|
||||
}
|
||||
|
||||
func (h *Chat) useCaseError(c echo.Context, err error) error {
|
||||
applicationError, ok := domain.AsApplicationError(err)
|
||||
if !ok {
|
||||
return err
|
||||
}
|
||||
status := http.StatusInternalServerError
|
||||
switch applicationError.Code {
|
||||
case "unsupported_media_type":
|
||||
status = http.StatusUnsupportedMediaType
|
||||
case "rate_limited":
|
||||
status = http.StatusTooManyRequests
|
||||
c.Response().Header().Set("Retry-After", "2")
|
||||
case "payload_too_large":
|
||||
status = http.StatusRequestEntityTooLarge
|
||||
case domain.ErrorUnavailable:
|
||||
status = http.StatusServiceUnavailable
|
||||
case domain.ErrorInvalid:
|
||||
status = http.StatusBadRequest
|
||||
case domain.ErrorUnauthorized:
|
||||
status = http.StatusUnauthorized
|
||||
challenge := `Bearer realm="messenger"`
|
||||
if c.Path() == "/api/v1/auth/sessions" {
|
||||
challenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
c.Response().Header().Set("WWW-Authenticate", challenge)
|
||||
case domain.ErrorNotFound:
|
||||
status = http.StatusNotFound
|
||||
case domain.ErrorConflict:
|
||||
status = http.StatusConflict
|
||||
}
|
||||
return h.writeError(c, status, string(applicationError.Code), applicationError.Message)
|
||||
}
|
||||
|
||||
func (h *Chat) writeError(c echo.Context, status int, code, message string) error {
|
||||
return c.JSON(status, dto.ErrorResponse{Error: dto.ErrorDetails{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestID(c),
|
||||
}})
|
||||
}
|
||||
|
||||
func (h *Chat) httpErrorHandler(err error, c echo.Context) {
|
||||
if c.Response().Committed {
|
||||
return
|
||||
}
|
||||
status := http.StatusInternalServerError
|
||||
code := "internal_error"
|
||||
message := "Внутренняя ошибка сервера"
|
||||
var httpError *echo.HTTPError
|
||||
if errors.As(err, &httpError) {
|
||||
status = httpError.Code
|
||||
switch status {
|
||||
case http.StatusNotFound:
|
||||
code, message = "not_found", "Объект не найден"
|
||||
case http.StatusMethodNotAllowed, http.StatusBadRequest:
|
||||
code, message = "invalid_request", "Некорректный запрос"
|
||||
}
|
||||
}
|
||||
_ = h.writeError(c, status, code, message)
|
||||
}
|
||||
|
||||
func requestID(c echo.Context) string {
|
||||
value, _ := c.Get(requestIDKey).(string)
|
||||
if value == "" {
|
||||
value = uuid.NewString()
|
||||
c.Set(requestIDKey, value)
|
||||
c.Response().Header().Set("X-Request-Id", value)
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) getChat(c echo.Context) error {
|
||||
request := dto.GetChatRequest{ChatID: c.Param("chat_id")}
|
||||
chat, ok, err := h.authorizedChat(c, getChatRequestToDomain(request))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return c.JSON(http.StatusOK, getChatResponseFromDomain(chat))
|
||||
}
|
||||
|
||||
func getChatRequestToDomain(request dto.GetChatRequest) domain.Chat {
|
||||
return domain.Chat{ID: request.ChatID}
|
||||
}
|
||||
|
||||
func getChatResponseFromDomain(chat domain.Chat) dto.GetChatResponse {
|
||||
return dto.GetChatResponse{
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) listChats(c echo.Context) error {
|
||||
limit, err := parseLimit(c)
|
||||
if err != nil {
|
||||
return h.invalid(c, err.Error())
|
||||
}
|
||||
rawCursor, cursorPresent, err := oneQueryValue(c, "cursor")
|
||||
if err != nil {
|
||||
return h.invalid(c, "cursor должен быть указан один раз")
|
||||
}
|
||||
request := dto.ListChatsRequest{Limit: limit, Cursor: rawCursor}
|
||||
userID := authenticatedUser(c).ID
|
||||
position, err := h.cursorPosition(request.Cursor, cursorPresent, "chats", userID)
|
||||
if err != nil {
|
||||
return h.invalid(c, "Некорректный cursor")
|
||||
}
|
||||
|
||||
page, err := h.useCase.ListChats(c.Request().Context(), userID, listChatsRequestToDomain(request, position))
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
var next *string
|
||||
if page.HasMore {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
encoded := h.cursor.encode("chats", userID, last.CreatedAt, last.ID)
|
||||
next = &encoded
|
||||
}
|
||||
return c.JSON(http.StatusOK, listChatsResponseFromDomain(page, next))
|
||||
}
|
||||
|
||||
func listChatsRequestToDomain(request dto.ListChatsRequest, position *domain.Position) domain.Pagination {
|
||||
return domain.Pagination{After: position, Limit: request.Limit}
|
||||
}
|
||||
|
||||
func listChatsResponseFromDomain(page domain.ChatPage, nextCursor *string) dto.ListChatsResponse {
|
||||
items := make([]dto.ListChatsItem, 0, len(page.Items))
|
||||
for _, chat := range page.Items {
|
||||
items = append(items, dto.ListChatsItem{
|
||||
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
|
||||
})
|
||||
}
|
||||
return dto.ListChatsResponse{Items: items, NextCursor: nextCursor}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
func (h *Chat) listMessages(c echo.Context) error {
|
||||
request := dto.ListMessagesRequest{ChatID: c.Param("chat_id")}
|
||||
chat, ok, err := h.authorizedChat(c, domain.Chat{ID: request.ChatID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
limit, err := parseLimit(c)
|
||||
if err != nil {
|
||||
return h.invalid(c, err.Error())
|
||||
}
|
||||
rawCursor, cursorPresent, err := oneQueryValue(c, "cursor")
|
||||
if err != nil {
|
||||
return h.invalid(c, "cursor должен быть указан один раз")
|
||||
}
|
||||
request.ChatID = chat.ID
|
||||
request.Limit = limit
|
||||
request.Cursor = rawCursor
|
||||
position, err := h.cursorPosition(request.Cursor, cursorPresent, "messages", request.ChatID)
|
||||
if err != nil {
|
||||
return h.invalid(c, "Некорректный cursor")
|
||||
}
|
||||
|
||||
page, err := h.useCase.ListMessages(
|
||||
c.Request().Context(), authenticatedUser(c).ID,
|
||||
listMessagesChatToDomain(request), listMessagesPaginationToDomain(request, position),
|
||||
)
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
var next *string
|
||||
if page.HasMore {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
encoded := h.cursor.encode("messages", request.ChatID, last.CreatedAt, last.ID)
|
||||
next = &encoded
|
||||
}
|
||||
return c.JSON(http.StatusOK, listMessagesResponseFromDomain(page, next))
|
||||
}
|
||||
|
||||
func listMessagesChatToDomain(request dto.ListMessagesRequest) domain.Chat {
|
||||
return domain.Chat{ID: request.ChatID}
|
||||
}
|
||||
|
||||
func listMessagesPaginationToDomain(request dto.ListMessagesRequest, position *domain.Position) domain.Pagination {
|
||||
return domain.Pagination{After: position, Limit: request.Limit}
|
||||
}
|
||||
|
||||
func listMessagesResponseFromDomain(page domain.MessagePage, nextCursor *string) dto.ListMessagesResponse {
|
||||
items := make([]dto.ListMessagesItem, 0, len(page.Items))
|
||||
for _, message := range page.Items {
|
||||
items = append(items, dto.ListMessagesItem{
|
||||
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
|
||||
Text: message.Text, AttachmentIDs: nonnilIDs(message.AttachmentIDs), CreatedAt: dto.Timestamp(message.CreatedAt),
|
||||
})
|
||||
}
|
||||
return dto.ListMessagesResponse{Items: items, NextCursor: nextCursor}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
)
|
||||
|
||||
func (h *Chat) liveness(c echo.Context) error {
|
||||
return c.JSON(http.StatusOK, dto.LivenessResponse{Status: "ok"})
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
requestIDKey = "request_id"
|
||||
userKey = "current_user"
|
||||
)
|
||||
|
||||
func (h *Chat) requestIDMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
requestID := uuid.NewString()
|
||||
c.Set(requestIDKey, requestID)
|
||||
c.Response().Header().Set("X-Request-Id", requestID)
|
||||
c.Response().Header().Set("X-Instance-Id", h.instanceID)
|
||||
if h.draining.Load() && c.Request().URL.Path != "/health/live" {
|
||||
return h.writeError(c, http.StatusServiceUnavailable, "unavailable", "Реплика завершает работу")
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Chat) authenticate(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
user, err := h.useCase.Authenticate(c.Request().Context(), bearerToken(c))
|
||||
if err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
c.Set(userKey, user)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
|
||||
func authenticatedUser(c echo.Context) domain.User {
|
||||
return c.Get(userKey).(domain.User)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
|
||||
)
|
||||
|
||||
func (h *Chat) readiness(c echo.Context) error {
|
||||
ctx, cancel := context.WithTimeout(c.Request().Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := h.useCase.Ready(ctx); err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
if h.attachments != nil {
|
||||
if err := h.attachments.Ready(ctx); err != nil {
|
||||
return h.useCaseError(c, err)
|
||||
}
|
||||
}
|
||||
return c.JSON(http.StatusOK, dto.ReadinessResponse{Status: "ok"})
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultLimit = 50
|
||||
maxLimit = 100
|
||||
maxJSONBody = 1 << 20
|
||||
)
|
||||
|
||||
var errUnsupportedMediaType = errors.New("unsupported media type")
|
||||
|
||||
func decodeJSON(c echo.Context, target any) error {
|
||||
mediaType, _, err := mime.ParseMediaType(c.Request().Header.Get(echo.HeaderContentType))
|
||||
if err != nil || mediaType != echo.MIMEApplicationJSON {
|
||||
return errUnsupportedMediaType
|
||||
}
|
||||
reader := http.MaxBytesReader(c.Response(), c.Request().Body, maxJSONBody)
|
||||
decoder := json.NewDecoder(reader)
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
return err
|
||||
}
|
||||
return errors.New("Некорректное JSON-тело")
|
||||
}
|
||||
var extra any
|
||||
err = decoder.Decode(&extra)
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
return err
|
||||
}
|
||||
if !errors.Is(err, io.EOF) {
|
||||
return errors.New("JSON-тело должно содержать ровно один объект")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseLimit(c echo.Context) (int, error) {
|
||||
raw, present, err := oneQueryValue(c, "limit")
|
||||
if err != nil {
|
||||
return 0, errors.New("limit должен быть указан один раз")
|
||||
}
|
||||
if !present {
|
||||
return defaultLimit, nil
|
||||
}
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxLimit {
|
||||
return 0, fmt.Errorf("limit должен быть целым числом от 1 до %d", maxLimit)
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
func oneQueryValue(c echo.Context, name string) (string, bool, error) {
|
||||
values, present := c.QueryParams()[name]
|
||||
if !present {
|
||||
return "", false, nil
|
||||
}
|
||||
if len(values) != 1 {
|
||||
return "", true, errors.New("query parameter must occur once")
|
||||
}
|
||||
return values[0], true, nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/attachment"
|
||||
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/observability"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
"github.com/swaggest/swgui/v5emb"
|
||||
)
|
||||
|
||||
// Chat is the HTTP handler and depends only on the application boundary.
|
||||
type Chat struct {
|
||||
attachments *attachment.Service
|
||||
loginLimit func(context.Context, string) (int, error)
|
||||
instanceID string
|
||||
draining atomic.Bool
|
||||
useCase UseCase
|
||||
cursor cursorCodec
|
||||
}
|
||||
|
||||
func NewChat(useCase UseCase, cursorKey [32]byte) *Chat {
|
||||
instanceID := os.Getenv("INSTANCE_ID")
|
||||
if instanceID == "" {
|
||||
instanceID, _ = os.Hostname()
|
||||
}
|
||||
if instanceID == "" {
|
||||
instanceID = uuid.NewString()
|
||||
}
|
||||
return &Chat{useCase: useCase, cursor: cursorCodec{secret: cursorKey}, instanceID: instanceID}
|
||||
}
|
||||
|
||||
func (h *Chat) WithLoginLimit(limit func(context.Context, string) (int, error)) *Chat {
|
||||
h.loginLimit = limit
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *Chat) Drain() { h.draining.Store(true) }
|
||||
|
||||
func (h *Chat) Router() *echo.Echo {
|
||||
e := echo.New()
|
||||
e.HideBanner = true
|
||||
e.HidePort = true
|
||||
e.HTTPErrorHandler = h.httpErrorHandler
|
||||
e.Use(h.requestIDMiddleware)
|
||||
e.Use(observability.Middleware)
|
||||
e.Use(middleware.Recover())
|
||||
|
||||
e.GET("/health/live", h.liveness)
|
||||
e.GET("/health/ready", h.readiness)
|
||||
swaggerUI := echo.WrapHandler(v5emb.New(
|
||||
"MTUSI Messenger",
|
||||
"/swagger/openapi.json",
|
||||
"/swagger/",
|
||||
))
|
||||
e.GET("/swagger", h.swagger)
|
||||
e.GET("/swagger/", swaggerUI)
|
||||
e.GET("/swagger/openapi.json", h.swaggerSpec)
|
||||
e.GET("/swagger/*", swaggerUI)
|
||||
e.POST("/api/v1/users", h.createUser)
|
||||
|
||||
e.POST("/api/v1/auth/sessions", h.createSession)
|
||||
|
||||
api := e.Group("/api/v1", h.authenticate)
|
||||
api.GET("/users/me", h.currentUser)
|
||||
api.DELETE("/auth/sessions/current", h.deleteSession)
|
||||
api.POST("/chats", h.createChat)
|
||||
api.GET("/chats", h.listChats)
|
||||
api.GET("/chats/:chat_id", h.getChat)
|
||||
api.POST("/chats/:chat_id/messages", h.createMessage)
|
||||
api.GET("/chats/:chat_id/messages", h.listMessages)
|
||||
if h.attachments != nil {
|
||||
api.POST("/chats/:chat_id/attachments", h.uploadAttachment)
|
||||
api.GET("/attachments/:attachment_id", h.getAttachment)
|
||||
api.GET("/attachments/:attachment_id/content", h.attachmentContent)
|
||||
}
|
||||
|
||||
return e
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user