Реализовать защиту Lab7 и проверку отзыва worker
This commit is contained in:
+5
-40
@@ -1,41 +1,6 @@
|
|||||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
# Host ports bound to loopback. scripts/bootstrap.py copies this file once.
|
||||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
APP_PORT=8443
|
||||||
APP_HOST=0.0.0.0
|
BAO_PORT=8200
|
||||||
APP_PORT=8080
|
GRAFANA_PORT=3443
|
||||||
APP_ENV=lab
|
|
||||||
SESSION_TTL_SECONDS=3600
|
SESSION_TTL_SECONDS=3600
|
||||||
# Choose credentials locally. File paths contain no secret values.
|
# Runtime service credentials are provisioned in OpenBao, without .env values.
|
||||||
DATABASE_URL_FILE=/run/secrets/database_url
|
|
||||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
|
||||||
SESSION_STORE=postgres
|
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
|
||||||
API_REPLICAS=2
|
|
||||||
IDEMPOTENCY_TTL_SECONDS=86400
|
|
||||||
S3_ENDPOINT=https://s3:9000
|
|
||||||
S3_REGION=us-east-1
|
|
||||||
S3_BUCKET=messenger-attachments
|
|
||||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
|
||||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
|
||||||
MAX_UPLOAD_BYTES=10485760
|
|
||||||
MAX_IMAGE_PIXELS=40000000
|
|
||||||
BROKER_URL_FILE=/run/secrets/broker_url
|
|
||||||
WORKER_CONCURRENCY=2
|
|
||||||
JOB_MAX_ATTEMPTS=5
|
|
||||||
JOB_TIMEOUT_SECONDS=60
|
|
||||||
STAGING_RETENTION_SECONDS=86400
|
|
||||||
OTEL_SERVICE_NAME=messenger-api
|
|
||||||
# Worker must set a distinct service.name.
|
|
||||||
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
|
|
||||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
|
||||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
|
||||||
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix.
|
|
||||||
PUBLIC_BASE_URL=https://localhost:8443
|
|
||||||
TLS_CA_FILE=/run/secrets/ca.crt
|
|
||||||
TLS_CERT_FILE=/run/secrets/service.crt
|
|
||||||
TLS_KEY_FILE=/run/secrets/service.key
|
|
||||||
BAO_ADDR=https://openbao:8200
|
|
||||||
BAO_CACERT=/run/secrets/bao-ca.crt
|
|
||||||
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
|
|
||||||
ARGON2_MEMORY_KIB=19456
|
|
||||||
ARGON2_ITERATIONS=2
|
|
||||||
ARGON2_PARALLELISM=1
|
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
/scripts/restart.sh text eol=lf
|
||||||
|
/scripts/stop-one.sh text eol=lf
|
||||||
|
/infra/s3-init.sh text eol=lf
|
||||||
|
/infra/postgres/*.sh text eol=lf
|
||||||
|
/scripts/*.cmd text eol=crlf
|
||||||
|
/migrations/*.sql text eol=lf
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
name: Lab7 HTTPS integration
|
||||||
|
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
compose:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 45
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Create disposable local PKI and initialize OpenBao
|
||||||
|
run: |
|
||||||
|
python3 scripts/bootstrap.py
|
||||||
|
docker compose config --quiet
|
||||||
|
docker compose up -d openbao
|
||||||
|
python3 scripts/bao.py init
|
||||||
|
python3 scripts/bao.py provision
|
||||||
|
- name: Build and start the isolated stack
|
||||||
|
run: |
|
||||||
|
docker compose build api worker minio s3-init
|
||||||
|
docker compose up -d --no-build
|
||||||
|
python3 -c 'import sys; sys.path.insert(0, "student-tests"); import security; security.wait_api(security.api(), timeout=150)'
|
||||||
|
- name: Run the public contract and HTTPS checks
|
||||||
|
run: |
|
||||||
|
make check
|
||||||
|
make test CA_FILE=secrets/ca.crt
|
||||||
|
make test-security CA_FILE=secrets/ca.crt
|
||||||
|
- name: Stop containers and discard the ephemeral CI volumes
|
||||||
|
if: always()
|
||||||
|
run: docker compose down -v
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
FROM golang:1.27.4-bookworm@sha256:ce59b41415e2524ae99926fe1f37ce48ba8c194dcbd2a56a65436cdcefa2bd34 AS build
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY *.go ./
|
||||||
|
COPY migrations ./migrations
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/go-build CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /messenger .
|
||||||
|
FROM python:3.13.18-slim-bookworm@sha256:f0fa218d5b06f9b9235024fa061cde2cb141f726de52134471053d2d9b5324a3 AS worker
|
||||||
|
RUN pip install --no-cache-dir --only-binary=:all: Pillow==13.0.0
|
||||||
|
COPY --from=build /messenger /messenger
|
||||||
|
COPY pipeline.py /pipeline.py
|
||||||
|
USER 65532:65532
|
||||||
|
STOPSIGNAL SIGTERM
|
||||||
|
ENTRYPOINT ["/messenger"]
|
||||||
|
|
||||||
|
FROM scratch AS api
|
||||||
|
COPY --from=build /messenger /messenger
|
||||||
|
USER 65532:65532
|
||||||
|
ENV APP_HOST=0.0.0.0 APP_PORT=8080 GOMEMLIMIT=256MiB
|
||||||
|
EXPOSE 8080
|
||||||
|
STOPSIGNAL SIGTERM
|
||||||
|
ENTRYPOINT ["/messenger"]
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# Build official sources: upstream registry images are no longer public.
|
||||||
|
FROM golang:1.27.3-bookworm@sha256:d9b6a1beb9474adc2a1ce842573639b44b2a0dd49b6669f51d3821baf9ec37c9 AS build
|
||||||
|
ENV GOTOOLCHAIN=local CGO_ENABLED=0
|
||||||
|
RUN go install -p 4 github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648
|
||||||
|
RUN go install -p 4 github.com/minio/mc@v0.0.0-20250813083541-7394ce0dd2a8
|
||||||
|
FROM alpine:3.23.3@sha256:25109184c71bdad752c8312a8623239686a9a2071e8825f20acb8f2198c3f659 AS tools
|
||||||
|
COPY --from=build /go/bin/mc /usr/bin/mc
|
||||||
|
ENTRYPOINT ["/usr/bin/mc"]
|
||||||
|
FROM scratch AS server
|
||||||
|
COPY --from=build /go/bin/minio /usr/bin/minio
|
||||||
|
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||||
|
ENTRYPOINT ["/usr/bin/minio"]
|
||||||
@@ -1,37 +1,94 @@
|
|||||||
# Отчёт — лабораторная 7
|
# Отчёт — лабораторная 7
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор и группа — Ситосенко, БВТ2303.
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка — **5**, трек 1 «Компрометация worker».
|
||||||
- Commit/PR: TODO после публикации
|
- Ветка решения — `solution/bvt2303-sitosenko`.
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Codex использован для реализации, тестов, анализа и оформления. Основа — собственное решение Lab6. [OpenBao cert auth](https://openbao.org/docs/auth/cert/) · [Аудит OpenBao](https://openbao.org/docs/audit/) · [Защита паролей OWASP](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html) · [Valkey ACL](https://valkey.io/topics/acl/) · [PostgreSQL pg_hba.conf](https://www.postgresql.org/docs/17/auth-pg-hba-conf.html)
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Нужны Docker с Linux-контейнерами, Compose v2, Python 3.9+, OpenSSL 3 и доступ к реестрам зависимостей при сборке. Порты 8443, 8200 и 3443 должны быть свободны. На Windows используйте Python с `-X utf8` или установите `$env:PYTHONUTF8 = '1'`. Bootstrap сохраняет существующие ключи. Операторские файлы остаются в `secrets/operator/`, с mode 0700 на Linux или отдельным ACL на Windows. Директорию следует держать под контролем оператора и резервировать отдельно от volume OpenBao.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/bootstrap.py
|
||||||
|
docker compose config --quiet
|
||||||
|
docker compose up -d openbao
|
||||||
|
python3 scripts/bao.py init
|
||||||
|
python3 scripts/bao.py provision
|
||||||
|
docker compose build api worker minio s3-init
|
||||||
|
docker compose up -d --no-build
|
||||||
|
python3 -c 'import sys; sys.path.insert(0, "student-tests"); import security; security.wait_api(security.api(), timeout=150)'
|
||||||
|
make check
|
||||||
|
make test CA_FILE=secrets/ca.crt
|
||||||
|
make test-security CA_FILE=secrets/ca.crt
|
||||||
|
```
|
||||||
|
|
||||||
|
На Windows команды `python -X utf8 scripts/check_contract.py`, `python -X utf8 tests/smoke.py --ca-file secrets/ca.crt --base-url https://127.0.0.1:8443` и `python -X utf8 tests/security.py --ca-file secrets/ca.crt --base-url https://127.0.0.1:8443` выполняют те же публичные проверки. Не устанавливайте CA глобально ради стенда. При вызове тестов передайте его открытый сертификат явно.
|
||||||
|
|
||||||
|
OpenBao запускается обычным сервером с хранилищем PebbleDB на постоянном томе. `init` делает инициализацию и явный unseal от имени оператора. При последующих запусках OpenBao после рестарта достаточно `python3 scripts/bao.py unseal`. Сервисы аутентифицируются своими сертификатами. Только одноразовые `migrate` и `s3-init` получают операторские credentials конкретной зависимости. Grafana доступна по `https://localhost:3443` под `admin`. Начальный пароль находится в локальном `secrets/grafana_password`.
|
||||||
|
|
||||||
|
- `docker compose stop` останавливает стенд с сохранением контейнеров и томов.
|
||||||
|
- `docker compose down` удаляет контейнеры и сети, сохраняя данные в named volumes. После запуска сначала явно распечатайте OpenBao.
|
||||||
|
- `docker compose down -v` намеренно удаляет учебные данные всех томов данного проекта. Старый файл OpenBao recovery больше не соответствует новому пустому volume. Для независимого повторного эксперимента заведите отдельный checkout с чистыми локальными секретами и отдельным Compose project name.
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
HAProxy передаёт HTTPS-запросы по mTLS двум API-репликам. PostgreSQL хранит аккаунты, членство, сообщения, метаданные и durable outbox. API загружает исходник в staging, затем в одной транзакции PostgreSQL фиксирует вложение и задание. Dispatcher публикует в Valkey Streams, worker получает работу и применяет lease, номер попытки и версию. Он записывает бинарные варианты в S3, фиксирует ready в PostgreSQL и подтверждает delivery. Повторная доставка сверяется с состоянием задания, а просроченные leases возвращает dispatcher. Idempotency-Key веб-API остаётся общим для обеих реплик.
|
||||||
|
|
||||||
|
Из Lab6 перенесены бизнес-API, миграции 001–006, outbox/версионирование, instrumentation, Grafana provisioning и правила Prometheus. Новые миграции назначают отдельные права сервиса. Контракты и публичные тесты сверяются с `20afc2c`. Рабочая матрица находится в [security/TRUST_MATRIX.md](security/TRUST_MATRIX.md), пути атак и контроли — в [модели угроз](security/THREAT_MODEL.md).
|
||||||
|
|
||||||
|
| Роль | Сервис и версия | Состояние и готовность |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| API, dispatcher, worker, шлюзы | Go 1.27.4, pgx 5.13.0, Go OTel SDK 1.47.0, Pillow 13.0.0 для worker | API readiness проверяет PostgreSQL, Valkey и S3. Все три процесса получают пакеты из OpenBao |
|
||||||
|
| Вход | HAProxy 3.2.6-alpine | HTTPS 8443 на loopback и mTLS health checks с проверкой SAN к API |
|
||||||
|
| Данные и миграции | PostgreSQL 17.6-bookworm, `migrate` | `pgdata`, SQL 001–008, `pg_isready` и startup check |
|
||||||
|
| Сессии и поток | Valkey 8.1.3-bookworm | Раздельные `sessions` и `brokerdata`, AOF `always`. Broker отдельно проксируется по mTLS |
|
||||||
|
| Объекты | MinIO из исходника 9e49d5e7a648 и mc 7394ce0dd2a8 | `objects`, приватный bucket, TLS `s3` → `minio`, готовность через `s3-init` |
|
||||||
|
| Приём OTel | Collector contrib 0.133.0 | Три bounded OTLP очереди. `/metrics` Collector читает Prometheus с отдельным leaf |
|
||||||
|
| Хранилища OTel | Prometheus 3.5.0, Loki 3.5.3, Tempo 2.8.2 | TLS на gateway, named volumes `metrics`, `logs`, `traces` |
|
||||||
|
| Визуализация | Grafana 12.1.1 | Named volume `dashboards`, HTTPS и пароль. Отдельный mTLS клиент к источникам |
|
||||||
|
| Secrets | OpenBao 2.7.3 | Volume `bao-data`, pinned leaf auth, KV v2, файл аудита с HMAC |
|
||||||
|
|
||||||
|
`.env` задаёт порты хоста и TTL сессии. Остальные параметры из worksheet `.env.example` задаёт Compose или код. PostgreSQL, Valkey, broker, cursor и S3 access key берутся из KV, поэтому *_FILE из worksheet не используются для рабочих сервисов. Набор leaf и CA монтируется в `/run/lab-tls`. API имеет отдельный server leaf. Размер загрузки — 10 MiB, верхний предел — 40 млн пикселей. Worker использует один процесс Pillow с deadline 30 с, 1 CPU, 640 MiB и отдельным tmpfs 32 MiB. API и worker запускаются под UID 65532. Файловые системы контейнеров read-only, named volumes или tmpfs дают только требуемые точки записи. PostgreSQL сохраняет ограниченный набор capabilities для подготовки ключа и перехода с root entrypoint на postgres. Сетевых host mode, privileged и Docker socket в Compose нет.
|
||||||
|
|
||||||
|
HTTP metrics используют шаблон маршрута и класс статуса. Серии `messenger_http_requests_total` и `messenger_http_duration_seconds_bucket` лежат в Prometheus. Worker публикует `messenger_job_attempts_total` и `messenger_job_duration_seconds_bucket`. Backlog контролируется возрастом и глубиной очереди. W3C Trace Context переносится в PostgreSQL и Valkey Stream. Loki сохраняет `request_id` и `trace_id`, Tempo связывает реальные spans. В labels нет UUID пользователей, raw URL, текста или credentials.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Совместимость | `make check`, `make validate`, `make test CA_FILE=secrets/ca.crt` | Структура и схема валидны, пользовательский сценарий работает по HTTPS | [Проверки](evidence/verification.txt) |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Доверенный ingress, проверка hostname, обе реплики | `make test-security`, `python3 student-tests/security.py security` | Внешний untrusted CA отклонён. На внутренних listener проверяются CA, серверный SAN и client identity | [Проверки](evidence/verification.txt) |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Пароли, rehash, общие лимиты, logout, expiry и upload ACL | `go test`, `python3 student-tests/security.py security`, `python3 student-tests/security.py expiry` | Параметры и методы приведены в разделе экспериментов | [Проверки](evidence/verification.txt) |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| mTLS broker/Collector, backend TLS, минимальные права, наблюдаемость | `python3 student-tests/security.py security` и `track` | Три варианта неверных leaf, scope на операции и раздельные source/ingest identities | [Проверки](evidence/verification.txt) |
|
||||||
|
| OpenBao persistent, scoped, expiry и controlled recovery | `python3 scripts/bao.py provision`, `python3 student-tests/security.py sealed` | Проверяются policy, seal и восстановление после unseal | [Проверки](evidence/verification.txt) |
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
| Рестарт и отказ реплики через HTTPS | `make test-persistence ACTION_SCRIPT=scripts/restart.sh CA_FILE=secrets/ca.crt`, `make test-failover ACTION_SCRIPT=scripts/stop-one.sh CA_FILE=secrets/ca.crt`, `python3 student-tests/security.py failover-all` | Рестарт подтверждён по `StartedAt` 15 контейнеров. Публичный тест сверяет подтверждённые записи, отдельный сценарий выбирает каждую реплику | [Проверки](evidence/verification.txt) |
|
||||||
|
| Скан зависимостей и образов | `govulncheck ./...` и локальный Trivy | Интерпретация по ролям и фактическим путям вызовов | [Разбор](security/SCANS.md) |
|
||||||
|
| Трек 1 | `python3 student-tests/security.py track --count 10` | Worker использует ограниченные права. После отзыва и ротации сверяются все принятые задания и SHA-256 оригиналов | [Проверки](evidence/verification.txt) |
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Гипотеза трека. Если доступ worker ограничен его задачами, владение его credentials оставляет права на обработку уже назначенных изображений. Запреты на чтение сообщений и hash, изменение владельца, перечисление bucket и публикацию должны срабатывать. При отзыве старый leaf и рабочие credentials теряют доступ, принятые задания остаются в durable outbox и потоке.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
Конфигурация Lab6 давала процессам общий PostgreSQL login владельца базы и общий пароль брокера. Worker мог перечислять весь bucket и удалять staging. В Lab7 условная компрометация моделируется входом с реальными credentials из KV роли worker. После разогрева одним обработанным PNG основной worker остановлен. Два параллельных клиента отправляют по HTTPS 10 маленьких PNG и создают сообщения с queued-вложениями. Операторский probe под identity worker проверяет SQLSTATE, коды S3, ACL broker и положительный OTLP. После замены leaf и паролей PostgreSQL и S3 проверяются отказы на новых соединениях со старым комплектом. Новая identity обрабатывает backlog. Тест сверяет все статусы, связи с сообщениями и SHA-256 загруженных байтов, затем повторяет отрицательные проверки прав. Это сравнение конфигурации Lab6 с измерением ограниченной роли Lab7.
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| TODO | TODO | TODO | TODO |
|
| Два повтора на i5-12450H, Docker Linux/amd64 | Прогон 1 | Прогон 2 |
|
||||||
|
| --- | ---: | ---: |
|
||||||
|
| Принято / ready / потеряно | 10 / 10 / 0 | 10 / 10 / 0 |
|
||||||
|
| Принятых вложений в секунду за короткий burst | 15.35 | 34.41 |
|
||||||
|
| p50 / p95 / p99 для upload и записи сообщения, мс | 71.4 / 100.0 / 100.0 | 48.3 / 74.9 / 74.9 |
|
||||||
|
| От запуска ротации до возврата команды активации worker, с | 5.40 | 6.19 |
|
||||||
|
| От активации до сверки всех ready и оригиналов, с | 1.77 | 1.78 |
|
||||||
|
| От остановки worker до сверки всех ready и оригиналов, с | 9.59 | 9.23 |
|
||||||
|
|
||||||
|
Для p95 и p99 при десяти измерениях берётся верхняя точка методом nearest rank. Интервал включает HTTPS upload и создание сообщения, поэтому результат описывает синтетический burst стенда. Контрольный отказ учитывает время проб, ротации и проверки содержимого. Исходные значения приведены в [evidence/verification.txt](evidence/verification.txt).
|
||||||
|
|
||||||
|
В контрольном прогоне после исправлений зависимостей и экспорта OTLP ещё 10 из 10 вложений дошли до ready, с сохранёнными сообщениями и SHA-256. Сверка всех результатов заняла 3.41 с с момента активации worker. Полное окно остановки, проб и ротации составило 27.01 с. Этот контроль выполнялся параллельно с локальным сканированием образа и приведён отдельно от двух основных замеров.
|
||||||
|
|
||||||
|
Argon2id хранит PHC строку с независимым salt 16 B и параметрами. Старый поддерживаемый профиль 19 MiB, t=2, p=1 обновляется после проверки пароля через условный UPDATE по предыдущему хешу. Рабочий профиль — 64 MiB, t=3, p=1. Бенчмарк с `GOMAXPROCS=1`, 3 серии по 8 операций на i5-12450H дал 19.6–23.7 мс для 19 MiB и 122.4–128.9 мс для 64 MiB. Выделяется около 64 MiB на операцию. Два слота на реплику ограничивают одновременный объём KDF примерно 128 MiB. Общее окно login допускает 24 попытки за 5 с, окно username — 6 за 30 с. Регистрации имеют отдельное общее окно и используют те же слоты KDF. Доступ при отказе Valkey не открывается.
|
||||||
|
|
||||||
|
После публичного останова реплики первое подтверждение записи после завершения hook пришло через 2.485 с. Последующие прогоны дали 2.858–3.831 с. История, вложение и уже существующая сессия сохранились. При seal OpenBao стенд сразу продолжил работу с действующим lease. Через 41.51 с проверки получили 503 по доверенному HTTPS. Через 1.91 с после unseal снова получен 200. Прогоны с отказами выполнялись последовательно.
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
Один учебный хост и один экземпляр каждого stateful backend. Выход хоста из строя не покрывается. В эксперименте worker сохраняет доступ к чужим изображениям в пределах staging и может менять доступные ему данные pipeline. Эти права нужны для обработки очереди. Эксперимент с отзывом не возвращает данные, уже прочитанные ранее. Продолжительность хранения root/unseal и leaf соответствует синтетическому стенду. Оператор подписывает короткоживущие leaf и обновляет их вручную. Автоматический CA rollover относится к отдельному треку задания. При блокировке OpenBao процессы сохраняют доступ только до окончания последнего lease и затем останавливаются. Один OpenBao остаётся зависимостью доступности.
|
||||||
|
|||||||
+321
@@ -0,0 +1,321 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"image"
|
||||||
|
_ "image/jpeg"
|
||||||
|
_ "image/png"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/minio/minio-go/v7"
|
||||||
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxUploadBytes int64 = 10 * 1024 * 1024
|
||||||
|
const maxImagePixels int64 = 40000000
|
||||||
|
|
||||||
|
type Variant struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
SizeBytes int64 `json:"size_bytes"`
|
||||||
|
Width int `json:"width"`
|
||||||
|
Height int `json:"height"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Attachment struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
ChatID string `json:"chat_id"`
|
||||||
|
OwnerID string `json:"owner_id"`
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
SizeBytes int64 `json:"size_bytes"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Variants []Variant `json:"variants"`
|
||||||
|
ErrorCode *string `json:"error_code"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
UpdatedAt string `json:"updated_at"`
|
||||||
|
resultVersion int
|
||||||
|
}
|
||||||
|
|
||||||
|
func s3Client(secrets serviceSecrets) (*minio.Client, string, error) {
|
||||||
|
endpoint, err := url.Parse(env("S3_ENDPOINT", "https://s3:9000"))
|
||||||
|
if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || endpoint.User != nil || endpoint.RawQuery != "" || endpoint.Fragment != "" || (endpoint.Path != "" && endpoint.Path != "/") {
|
||||||
|
return nil, "", errors.New("invalid S3 endpoint")
|
||||||
|
}
|
||||||
|
if secrets.S3User == "" || secrets.S3Password == "" {
|
||||||
|
return nil, "", errors.New("missing scoped S3 credentials")
|
||||||
|
}
|
||||||
|
transport, err := labHTTPTransport(false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", err
|
||||||
|
}
|
||||||
|
client, err := minio.New(endpoint.Host, &minio.Options{Creds: credentials.NewStaticV4(secrets.S3User, secrets.S3Password, ""), Secure: true, Region: env("S3_REGION", "us-east-1"), Transport: transport, MaxRetries: 1, BucketLookup: minio.BucketLookupPath})
|
||||||
|
return client, env("S3_BUCKET", "messenger-attachments"), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func validFilename(s string) bool {
|
||||||
|
if !utf8.ValidString(s) || strings.TrimSpace(s) == "" || utf8.RuneCountInString(s) > 255 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, c := range s {
|
||||||
|
if c == '/' || c == '\\' || unicode.IsControl(c) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func messageFields(body map[string]json.RawMessage) (string, []string, error) {
|
||||||
|
var text string
|
||||||
|
if string(body["text"]) == "null" || json.Unmarshal(body["text"], &text) != nil || utf8.RuneCountInString(text) > 4000 {
|
||||||
|
return "", nil, invalid()
|
||||||
|
}
|
||||||
|
ids := []string{}
|
||||||
|
if raw, ok := body["attachment_ids"]; ok {
|
||||||
|
if string(raw) == "null" || json.Unmarshal(raw, &ids) != nil || len(ids) > 10 {
|
||||||
|
return "", nil, invalid()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for i, id := range ids {
|
||||||
|
normalized, err := normalizeID(id)
|
||||||
|
if err != nil || seen[normalized] {
|
||||||
|
return "", nil, invalid()
|
||||||
|
}
|
||||||
|
ids[i] = normalized
|
||||||
|
seen[normalized] = true
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(text) == "" && len(ids) == 0 {
|
||||||
|
return "", nil, invalid()
|
||||||
|
}
|
||||||
|
return text, ids, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) s3Ready(ctx context.Context) bool {
|
||||||
|
check, cancel := context.WithTimeout(ctx, time.Second)
|
||||||
|
defer cancel()
|
||||||
|
ok, err := a.s3.BucketExists(check, a.bucket)
|
||||||
|
return err == nil && ok
|
||||||
|
}
|
||||||
|
func mediaError() error {
|
||||||
|
return apiError{415, "unsupported_media_type", "Expected a valid PNG or JPEG matching Content-Type"}
|
||||||
|
}
|
||||||
|
func tooLarge() error { return apiError{413, "payload_too_large", "Image exceeds byte or pixel limit"} }
|
||||||
|
|
||||||
|
// The encoded file lives only in a bounded tmpfs during validation/PUT. At most
|
||||||
|
// five uploads and one decoded image per process; no bytes enter PostgreSQL.
|
||||||
|
func (a *App) upload(ctx context.Context, w http.ResponseWriter, r *http.Request, chat, user string) (Attachment, error) {
|
||||||
|
result := Attachment{}
|
||||||
|
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||||
|
if err != nil || len(query) != 1 || len(query["filename"]) != 1 || !validFilename(query.Get("filename")) {
|
||||||
|
return result, invalid()
|
||||||
|
}
|
||||||
|
contentType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||||
|
if err != nil || len(params) != 0 || (contentType != "image/png" && contentType != "image/jpeg") {
|
||||||
|
return result, mediaError()
|
||||||
|
}
|
||||||
|
if r.ContentLength > maxUploadBytes {
|
||||||
|
return result, tooLarge()
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case a.uploadSlots <- struct{}{}:
|
||||||
|
defer func() { <-a.uploadSlots }()
|
||||||
|
default:
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
f, err := os.CreateTemp("", "upload-*")
|
||||||
|
if err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
defer os.Remove(f.Name())
|
||||||
|
defer f.Close()
|
||||||
|
digest := sha256.New()
|
||||||
|
size, err := io.Copy(io.MultiWriter(f, digest), http.MaxBytesReader(w, r.Body, maxUploadBytes))
|
||||||
|
if err != nil {
|
||||||
|
var big *http.MaxBytesError
|
||||||
|
if errors.As(err, &big) {
|
||||||
|
return result, tooLarge()
|
||||||
|
}
|
||||||
|
return result, invalid()
|
||||||
|
}
|
||||||
|
if size == 0 {
|
||||||
|
return result, mediaError()
|
||||||
|
}
|
||||||
|
if _, err = f.Seek(0, io.SeekStart); err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
cfg, format, err := image.DecodeConfig(f)
|
||||||
|
if err != nil || (format != "png" && format != "jpeg") || "image/"+format != contentType {
|
||||||
|
return result, mediaError()
|
||||||
|
}
|
||||||
|
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width) > maxImagePixels/int64(cfg.Height) {
|
||||||
|
return result, tooLarge()
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case a.decodeSlot <- struct{}{}:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
validation := func() error {
|
||||||
|
defer func() { <-a.decodeSlot }()
|
||||||
|
if _, e := f.Seek(0, io.SeekStart); e != nil {
|
||||||
|
return unavailable()
|
||||||
|
}
|
||||||
|
decoded, actual, e := image.Decode(f)
|
||||||
|
if e != nil || actual != format || decoded.Bounds().Dx() != cfg.Width || decoded.Bounds().Dy() != cfg.Height {
|
||||||
|
return mediaError()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err = validation(); err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
if _, err = f.Seek(0, io.SeekStart); err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
result = Attachment{ID: uuid(), ChatID: chat, OwnerID: user, Filename: query.Get("filename"), ContentType: contentType, SizeBytes: size, SHA256: hex.EncodeToString(digest.Sum(nil)), Status: "queued", Variants: []Variant{}}
|
||||||
|
tx, err := a.db.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
defer rollbackAttachment(tx)
|
||||||
|
if err = attachmentLock(ctx, tx, result.ID); err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
key := "original/" + result.ID
|
||||||
|
staging, s3Span := startSpan(ctx, "s3 put staging")
|
||||||
|
_, err = a.s3.PutObject(staging, a.bucket, stagingKey(result.ID), f, size, minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true, UserMetadata: map[string]string{"sha256": result.SHA256}})
|
||||||
|
endSpan(s3Span, err)
|
||||||
|
if err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
var created, updated time.Time
|
||||||
|
err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,owner_id,object_key,filename,content_type,size_bytes,sha256,status,active_version)
|
||||||
|
VALUES($1,$2,$3,$4,$5,$6,$7,$8,'queued',1) RETURNING created_at,updated_at`, result.ID, chat, user, key, result.Filename, contentType, size, result.SHA256).Scan(&created, &updated)
|
||||||
|
if err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
if err = enqueueImage(ctx, tx, result.ID, 1); err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
// COMMIT may have succeeded even when its acknowledgement is lost. Never
|
||||||
|
// blindly delete the blob here: reconciler checks durable metadata + grace.
|
||||||
|
if err = tx.Commit(ctx); err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
result.CreatedAt = stamp(created)
|
||||||
|
result.UpdatedAt = stamp(updated)
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func attachmentLock(ctx context.Context, tx pgx.Tx, id string) error {
|
||||||
|
_, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", "attachment:"+id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func rollbackAttachment(tx pgx.Tx) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
_ = tx.Rollback(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) attachment(ctx context.Context, id, user string) (Attachment, error) {
|
||||||
|
x := Attachment{}
|
||||||
|
var created, updated time.Time
|
||||||
|
var missingSince *time.Time
|
||||||
|
err := a.db.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.owner_id::text,a.filename,a.content_type,a.size_bytes,a.sha256,a.created_at,a.updated_at,a.missing_since,a.status,a.variants,a.error_code,a.result_version
|
||||||
|
FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id AND m.user_id=$2 WHERE a.id=$1`, id, user).Scan(&x.ID, &x.ChatID, &x.OwnerID, &x.Filename, &x.ContentType, &x.SizeBytes, &x.SHA256, &created, &updated, &missingSince, &x.Status, &x.Variants, &x.ErrorCode, &x.resultVersion)
|
||||||
|
if err != nil {
|
||||||
|
return x, dbError(err)
|
||||||
|
}
|
||||||
|
if missingSince != nil {
|
||||||
|
return x, unavailable()
|
||||||
|
}
|
||||||
|
x.CreatedAt = stamp(created)
|
||||||
|
x.UpdatedAt = stamp(updated)
|
||||||
|
return x, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type binaryContent struct {
|
||||||
|
attachment Attachment
|
||||||
|
object *minio.Object
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) content(ctx context.Context, r *http.Request, x Attachment) (binaryContent, error) {
|
||||||
|
q, err := url.ParseQuery(r.URL.RawQuery)
|
||||||
|
if err != nil || len(q) > 1 || len(q["variant"]) > 1 {
|
||||||
|
return binaryContent{}, invalid()
|
||||||
|
}
|
||||||
|
for k := range q {
|
||||||
|
if k != "variant" {
|
||||||
|
return binaryContent{}, invalid()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
name := "original"
|
||||||
|
if values, ok := q["variant"]; ok {
|
||||||
|
name = values[0]
|
||||||
|
switch name {
|
||||||
|
case "original", "thumbnail", "crop", "optimized":
|
||||||
|
default:
|
||||||
|
return binaryContent{}, invalid()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if x.Status != "ready" {
|
||||||
|
return binaryContent{}, apiError{409, "conflict", "Attachment is not ready"}
|
||||||
|
}
|
||||||
|
if name != "original" {
|
||||||
|
found := false
|
||||||
|
for _, variant := range x.Variants {
|
||||||
|
if variant.Name == name {
|
||||||
|
x.ContentType, x.SizeBytes = variant.ContentType, variant.SizeBytes
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
return binaryContent{}, missing()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
object, err := a.s3.GetObject(ctx, a.bucket, resultKey(x.ID, x.resultVersion, name), minio.GetObjectOptions{})
|
||||||
|
if err != nil {
|
||||||
|
return binaryContent{}, unavailable()
|
||||||
|
}
|
||||||
|
info, err := object.Stat()
|
||||||
|
if err != nil || info.Size != x.SizeBytes {
|
||||||
|
object.Close()
|
||||||
|
return binaryContent{}, unavailable()
|
||||||
|
}
|
||||||
|
return binaryContent{x, object}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeContent(w http.ResponseWriter, b binaryContent) {
|
||||||
|
defer b.object.Close()
|
||||||
|
w.Header().Set("Content-Type", b.attachment.ContentType)
|
||||||
|
w.Header().Set("Content-Length", strconv.FormatInt(b.attachment.SizeBytes, 10))
|
||||||
|
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": b.attachment.Filename}))
|
||||||
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
|
w.Header().Set("Cache-Control", "private, no-store")
|
||||||
|
w.WriteHeader(200)
|
||||||
|
if _, err := io.CopyN(w, b.object, b.attachment.SizeBytes); err != nil {
|
||||||
|
panic(http.ErrAbortHandler)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"golang.org/x/crypto/argon2"
|
||||||
|
)
|
||||||
|
|
||||||
|
func password(body map[string]json.RawMessage) (string, error) {
|
||||||
|
var p string
|
||||||
|
if json.Unmarshal(body["password"], &p) != nil || utf8.RuneCountInString(p) < 12 || utf8.RuneCountInString(p) > 128 {
|
||||||
|
return "", invalid()
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const argonCurrent = "m=65536,t=3,p=1"
|
||||||
|
const argonLegacy = "m=19456,t=2,p=1"
|
||||||
|
|
||||||
|
func hashPassword(p string) string {
|
||||||
|
return makePasswordHash(p, argonCurrent, 64*1024, 3)
|
||||||
|
}
|
||||||
|
|
||||||
|
func makePasswordHash(p, params string, memory, rounds uint32) string {
|
||||||
|
salt := make([]byte, 16)
|
||||||
|
if _, err := rand.Read(salt); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
key := argon2.IDKey([]byte(p), salt, rounds, memory, 1, 32)
|
||||||
|
return "$argon2id$v=19$" + params + "$" + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(key)
|
||||||
|
}
|
||||||
|
func verifyPassword(hash, p string) (valid bool, upgrade bool) {
|
||||||
|
parts := strings.Split(hash, "$")
|
||||||
|
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != "v=19" {
|
||||||
|
return false, false
|
||||||
|
}
|
||||||
|
var memory, rounds uint32
|
||||||
|
switch parts[3] {
|
||||||
|
case argonCurrent:
|
||||||
|
memory, rounds = 64*1024, 3
|
||||||
|
case argonLegacy:
|
||||||
|
memory, rounds = 19*1024, 2
|
||||||
|
default:
|
||||||
|
return false, false
|
||||||
|
}
|
||||||
|
salt, e := base64.RawStdEncoding.DecodeString(parts[4])
|
||||||
|
if e != nil || len(salt) != 16 {
|
||||||
|
return false, false
|
||||||
|
}
|
||||||
|
want, e := base64.RawStdEncoding.DecodeString(parts[5])
|
||||||
|
if e != nil || len(want) != 32 {
|
||||||
|
return false, false
|
||||||
|
}
|
||||||
|
actual := argon2.IDKey([]byte(p), salt, rounds, memory, 1, 32)
|
||||||
|
match := subtle.ConstantTimeCompare(want, actual) == 1
|
||||||
|
return match, match && parts[3] == argonLegacy
|
||||||
|
}
|
||||||
|
func (a *App) kdfSlot(ctx context.Context) error {
|
||||||
|
select {
|
||||||
|
case a.kdf <- struct{}{}:
|
||||||
|
return nil
|
||||||
|
case <-ctx.Done():
|
||||||
|
return unavailable()
|
||||||
|
default:
|
||||||
|
return apiError{429, "rate_limited", "Try again later"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var bumpLimit = redis.NewScript(`
|
||||||
|
local count = redis.call('INCR', KEYS[1])
|
||||||
|
if count == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
|
||||||
|
if count > tonumber(ARGV[2]) then return redis.call('TTL', KEYS[1]) + 1 end
|
||||||
|
return 0
|
||||||
|
`)
|
||||||
|
|
||||||
|
type limitError struct{ seconds int }
|
||||||
|
|
||||||
|
func (e limitError) Error() string { return "rate limited" }
|
||||||
|
|
||||||
|
func (a *App) rateLimit(ctx context.Context, scope string, count, seconds int) error {
|
||||||
|
retry, err := bumpLimit.Run(ctx, a.sessions, []string{"limit:" + scope}, strconv.Itoa(seconds), strconv.Itoa(count)).Int()
|
||||||
|
if err != nil {
|
||||||
|
return unavailable()
|
||||||
|
}
|
||||||
|
if retry > 0 {
|
||||||
|
return limitError{retry}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type storedSession struct {
|
||||||
|
UserID string `json:"user_id"`
|
||||||
|
ExpiresAt time.Time `json:"expires_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func sessionKey(token string) string {
|
||||||
|
h := sha256.Sum256([]byte(token))
|
||||||
|
return "sess:" + hex.EncodeToString(h[:])
|
||||||
|
}
|
||||||
|
func (a *App) authenticate(ctx context.Context, r *http.Request) (string, string, error) {
|
||||||
|
values := r.Header.Values("Authorization")
|
||||||
|
if len(values) != 1 {
|
||||||
|
return "", "", unauthorized()
|
||||||
|
}
|
||||||
|
parts := strings.Fields(values[0])
|
||||||
|
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||||
|
return "", "", unauthorized()
|
||||||
|
}
|
||||||
|
token, e := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if e != nil || len(token) != 32 {
|
||||||
|
return "", "", unauthorized()
|
||||||
|
}
|
||||||
|
key := sessionKey(parts[1])
|
||||||
|
raw, err := a.sessions.Get(ctx, key).Bytes()
|
||||||
|
if errors.Is(err, redis.Nil) {
|
||||||
|
return "", "", unauthorized()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", "", unavailable()
|
||||||
|
}
|
||||||
|
var session storedSession
|
||||||
|
if json.Unmarshal(raw, &session) != nil {
|
||||||
|
return "", "", unavailable()
|
||||||
|
}
|
||||||
|
if !time.Now().Before(session.ExpiresAt) {
|
||||||
|
return "", "", unauthorized()
|
||||||
|
}
|
||||||
|
if _, err = a.user(ctx, session.UserID); err != nil {
|
||||||
|
var ae apiError
|
||||||
|
if errors.As(err, &ae) && ae.status == 404 {
|
||||||
|
return "", "", unauthorized()
|
||||||
|
}
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
return session.UserID, key, nil
|
||||||
|
}
|
||||||
|
func (a *App) login(ctx context.Context, r *http.Request) (int, any, error) {
|
||||||
|
if err := a.rateLimit(ctx, "login", 24, 5); err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
if r.ContentLength > 0 || len(r.TransferEncoding) > 0 {
|
||||||
|
return 0, nil, invalid()
|
||||||
|
}
|
||||||
|
username, p, ok := r.BasicAuth()
|
||||||
|
if len(r.Header.Values("Authorization")) != 1 || !ok || !usernamePattern.MatchString(username) || !utf8.ValidString(p) || utf8.RuneCountInString(p) < 12 || utf8.RuneCountInString(p) > 128 {
|
||||||
|
return 0, nil, unauthorized()
|
||||||
|
}
|
||||||
|
nameKey := sha256.Sum256([]byte(username))
|
||||||
|
if err := a.rateLimit(ctx, "account:"+hex.EncodeToString(nameKey[:]), 6, 30); err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
var hash string
|
||||||
|
var u User
|
||||||
|
var created time.Time
|
||||||
|
err := a.db.QueryRow(ctx, "SELECT id::text,username,display_name,created_at,password_hash FROM users WHERE username=$1", username).Scan(&u.ID, &u.Username, utf8String{&u.DisplayName}, &created, &hash)
|
||||||
|
absent := errors.Is(err, pgx.ErrNoRows)
|
||||||
|
if err != nil && !absent {
|
||||||
|
return 0, nil, unavailable()
|
||||||
|
}
|
||||||
|
if absent {
|
||||||
|
hash = a.dummyHash
|
||||||
|
}
|
||||||
|
if err = a.kdfSlot(ctx); err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
valid, upgrade := verifyPassword(hash, p)
|
||||||
|
var replacement string
|
||||||
|
if valid && upgrade && !absent {
|
||||||
|
replacement = hashPassword(p)
|
||||||
|
}
|
||||||
|
<-a.kdf
|
||||||
|
if !valid || absent {
|
||||||
|
return 0, nil, unauthorized()
|
||||||
|
}
|
||||||
|
if replacement != "" {
|
||||||
|
result, err := a.db.Exec(ctx, "UPDATE users SET password_hash=$1 WHERE id=$2 AND password_hash=$3", replacement, u.ID, hash)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, unavailable()
|
||||||
|
}
|
||||||
|
if result.RowsAffected() == 0 {
|
||||||
|
if err := a.db.QueryRow(ctx, "SELECT password_hash FROM users WHERE id=$1", u.ID).Scan(&hash); err != nil {
|
||||||
|
return 0, nil, unavailable()
|
||||||
|
}
|
||||||
|
if err := a.kdfSlot(ctx); err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
matches, _ := verifyPassword(hash, p)
|
||||||
|
<-a.kdf
|
||||||
|
if !matches {
|
||||||
|
return 0, nil, unauthorized()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
u.CreatedAt = stamp(created)
|
||||||
|
tokenBytes := make([]byte, 32)
|
||||||
|
if _, err = rand.Read(tokenBytes); err != nil {
|
||||||
|
return 0, nil, unavailable()
|
||||||
|
}
|
||||||
|
token := base64.RawURLEncoding.EncodeToString(tokenBytes)
|
||||||
|
expires := time.Now().UTC().Truncate(time.Second).Add(a.ttl)
|
||||||
|
raw, _ := json.Marshal(storedSession{u.ID, expires})
|
||||||
|
if err = a.sessions.SetArgs(ctx, sessionKey(token), raw, redis.SetArgs{Mode: "NX", ExpireAt: expires}).Err(); err != nil {
|
||||||
|
return 0, nil, unavailable()
|
||||||
|
}
|
||||||
|
return 201, map[string]any{"token": token, "token_type": "Bearer", "expires_at": expires.Format(time.RFC3339), "user": u}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestArgonProfiles(t *testing.T) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name, hash string
|
||||||
|
match, upgrade bool
|
||||||
|
}{
|
||||||
|
{"current", hashPassword("test-password"), true, false},
|
||||||
|
{"legacy", makePasswordHash("test-password", argonLegacy, 19*1024, 2), true, true},
|
||||||
|
{"other password", hashPassword("other-password"), false, false},
|
||||||
|
{"unsupported parameters", "$argon2id$v=19$m=999999999,t=10,p=50$abcd$efgh", false, false},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
match, upgrade := verifyPassword(test.hash, "test-password")
|
||||||
|
if match != test.match || upgrade != test.upgrade {
|
||||||
|
t.Fatalf("verify = (%v, %v), want (%v, %v)", match, upgrade, test.match, test.upgrade)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkArgonVerification(b *testing.B) {
|
||||||
|
for _, test := range []struct {
|
||||||
|
name, params string
|
||||||
|
memory, rounds uint32
|
||||||
|
}{
|
||||||
|
{"19MiB-2", argonLegacy, 19 * 1024, 2},
|
||||||
|
{"64MiB-3", argonCurrent, 64 * 1024, 3},
|
||||||
|
} {
|
||||||
|
b.Run(test.name, func(b *testing.B) {
|
||||||
|
hash := makePasswordHash("benchmark-password", test.params, test.memory, test.rounds)
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.ResetTimer()
|
||||||
|
for range b.N {
|
||||||
|
if valid, _ := verifyPassword(hash, "benchmark-password"); !valid {
|
||||||
|
b.Fatal("benchmark hash rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type serviceSecrets struct {
|
||||||
|
DatabaseURL string `json:"database_url"`
|
||||||
|
CacheURL string `json:"cache_url"`
|
||||||
|
CursorKey string `json:"cursor_secret"`
|
||||||
|
BrokerURL string `json:"broker_url"`
|
||||||
|
S3User string `json:"s3_access_key_id"`
|
||||||
|
S3Password string `json:"s3_secret_access_key"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func baoCall(ctx context.Context, c *http.Client, endpoint, token string, input any, output any) error {
|
||||||
|
method := http.MethodGet
|
||||||
|
var body io.Reader
|
||||||
|
if input != nil {
|
||||||
|
method = http.MethodPost
|
||||||
|
encoded, err := json.Marshal(input)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("invalid secret request")
|
||||||
|
}
|
||||||
|
body = bytes.NewReader(encoded)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, endpoint, body)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("invalid secret endpoint")
|
||||||
|
}
|
||||||
|
if input != nil {
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
if token != "" {
|
||||||
|
req.Header.Set("X-Vault-Token", token)
|
||||||
|
}
|
||||||
|
res, err := c.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("secret service unavailable")
|
||||||
|
}
|
||||||
|
defer res.Body.Close()
|
||||||
|
if res.StatusCode != http.StatusOK || json.NewDecoder(io.LimitReader(res.Body, 32*1024)).Decode(output) != nil {
|
||||||
|
return errors.New("secret request rejected")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchSecrets(ctx context.Context, c *http.Client, address, role string) (serviceSecrets, time.Time, error) {
|
||||||
|
var auth struct {
|
||||||
|
Auth struct {
|
||||||
|
Token string `json:"client_token"`
|
||||||
|
TTL int `json:"lease_duration"`
|
||||||
|
} `json:"auth"`
|
||||||
|
}
|
||||||
|
started := time.Now()
|
||||||
|
if err := baoCall(ctx, c, address+"/v1/auth/cert/login", "", map[string]string{"name": role}, &auth); err != nil {
|
||||||
|
return serviceSecrets{}, time.Time{}, err
|
||||||
|
}
|
||||||
|
if auth.Auth.Token == "" || auth.Auth.TTL < 1 || auth.Auth.TTL > 60 {
|
||||||
|
return serviceSecrets{}, time.Time{}, errors.New("unexpected secret token lifetime")
|
||||||
|
}
|
||||||
|
var response struct {
|
||||||
|
Data struct {
|
||||||
|
Secrets serviceSecrets `json:"data"`
|
||||||
|
} `json:"data"`
|
||||||
|
}
|
||||||
|
err := baoCall(ctx, c, address+"/v1/lab/data/"+role, auth.Auth.Token, nil, &response)
|
||||||
|
return response.Data.Secrets, started.Add(time.Duration(auth.Auth.TTL) * time.Second), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func startSecrets(role string) (serviceSecrets, func(), error) {
|
||||||
|
address := env("BAO_ADDR", "https://openbao:8200")
|
||||||
|
endpoint, err := url.Parse(address)
|
||||||
|
if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || endpoint.User != nil ||
|
||||||
|
endpoint.Path != "" || endpoint.RawQuery != "" || endpoint.Fragment != "" {
|
||||||
|
return serviceSecrets{}, nil, errors.New("invalid OpenBao TLS endpoint")
|
||||||
|
}
|
||||||
|
transport, err := labHTTPTransport(true)
|
||||||
|
if err != nil {
|
||||||
|
return serviceSecrets{}, nil, err
|
||||||
|
}
|
||||||
|
c := &http.Client{Transport: transport, Timeout: 3 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||||
|
return http.ErrUseLastResponse
|
||||||
|
}}
|
||||||
|
ctx, stop := context.WithCancel(context.Background())
|
||||||
|
initial, expires, err := fetchSecrets(ctx, c, address, role)
|
||||||
|
if err != nil {
|
||||||
|
stop()
|
||||||
|
transport.CloseIdleConnections()
|
||||||
|
return serviceSecrets{}, nil, err
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
timer := time.NewTimer(time.Until(expires))
|
||||||
|
defer timer.Stop()
|
||||||
|
refresh := time.NewTicker(10 * time.Second)
|
||||||
|
defer refresh.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-timer.C:
|
||||||
|
slog.Warn("secret lease expired", "role", role)
|
||||||
|
os.Exit(1)
|
||||||
|
case <-refresh.C:
|
||||||
|
timeout, cancel := context.WithDeadline(ctx, expires)
|
||||||
|
current, next, err := fetchSecrets(timeout, c, address, role)
|
||||||
|
cancel()
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("secret refresh failed", "role", role)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if current != initial {
|
||||||
|
slog.Info("secret bundle changed", "role", role)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
expires = next
|
||||||
|
timer.Reset(time.Until(expires))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return initial, func() {
|
||||||
|
stop()
|
||||||
|
transport.CloseIdleConnections()
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
+361
@@ -0,0 +1,361 @@
|
|||||||
|
x-hardening: &hardening
|
||||||
|
read_only: true
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: [no-new-privileges:true]
|
||||||
|
pids_limit: 128
|
||||||
|
logging:
|
||||||
|
options: {max-size: 10m, max-file: "2"}
|
||||||
|
|
||||||
|
x-app: &app
|
||||||
|
<<: *hardening
|
||||||
|
image: mtusi-messenger:lab7
|
||||||
|
build: {context: ., target: api}
|
||||||
|
restart: unless-stopped
|
||||||
|
tmpfs: ["/tmp:size=32m,mode=1777,noexec,nosuid,nodev"]
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 1.0
|
||||||
|
|
||||||
|
x-app-env: &app-env
|
||||||
|
BAO_ADDR: https://openbao:8200
|
||||||
|
S3_ENDPOINT: https://s3:9000
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||||
|
GOMEMLIMIT: 128MiB
|
||||||
|
|
||||||
|
x-gateway: &gateway
|
||||||
|
<<: *app
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.5
|
||||||
|
environment: {GOMEMLIMIT: 64MiB}
|
||||||
|
|
||||||
|
x-stateful: &stateful
|
||||||
|
<<: *hardening
|
||||||
|
tmpfs: ["/tmp:size=32m,mode=1777,noexec,nosuid,nodev"]
|
||||||
|
mem_limit: 384m
|
||||||
|
cpus: 0.75
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
<<: *stateful
|
||||||
|
image: postgres:17.6-bookworm@sha256:f3bd19c606e442c3d7bdfa8002e03fe260a1023351e0ea4598032022b68dd6e3
|
||||||
|
entrypoint: [/bin/sh, /bootstrap/entrypoint.sh]
|
||||||
|
command: [postgres, -c, ssl=on, -c, ssl_min_protocol_version=TLSv1.2,
|
||||||
|
-c, ssl_cert_file=/run/lab-tls/tls.crt, -c, ssl_key_file=/tmp/postgres.key,
|
||||||
|
-c, hba_file=/bootstrap/pg_hba.conf]
|
||||||
|
cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID]
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: messenger
|
||||||
|
POSTGRES_DB: messenger
|
||||||
|
POSTGRES_PASSWORD_FILE: /run/db-secret/postgres
|
||||||
|
POSTGRES_INITDB_ARGS: --auth-host=scram-sha-256
|
||||||
|
volumes:
|
||||||
|
- pgdata:/var/lib/postgresql/data
|
||||||
|
- ./secrets/db:/run/db-secret:ro
|
||||||
|
- ./secrets/tls/db:/run/lab-tls:ro
|
||||||
|
- ./infra/postgres:/bootstrap:ro
|
||||||
|
- ./infra/postgres/01-roles.sh:/docker-entrypoint-initdb.d/01-roles.sh:ro
|
||||||
|
tmpfs: ["/tmp:size=32m,mode=1777,noexec,nosuid,nodev", "/var/run/postgresql:size=8m,mode=3777"]
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD-SHELL, "pg_isready -h 127.0.0.1 -U messenger -d messenger"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 2s
|
||||||
|
retries: 30
|
||||||
|
|
||||||
|
valkey:
|
||||||
|
<<: *stateful
|
||||||
|
image: valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571
|
||||||
|
user: "999:1000"
|
||||||
|
command: [valkey-server, /etc/lab.conf]
|
||||||
|
mem_limit: 256m
|
||||||
|
volumes:
|
||||||
|
- sessions:/data
|
||||||
|
- ./secrets/acl/sessions:/run/lab-acl/sessions:ro
|
||||||
|
- ./secrets/tls/valkey:/run/lab-tls:ro
|
||||||
|
- ./infra/valkey-sessions.conf:/etc/lab.conf:ro
|
||||||
|
|
||||||
|
broker:
|
||||||
|
<<: *gateway
|
||||||
|
command: [gateway, broker]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/broker:/run/lab-tls:ro
|
||||||
|
- ./secrets/revocation:/run/lab-revocation:ro
|
||||||
|
|
||||||
|
broker-store:
|
||||||
|
<<: *stateful
|
||||||
|
image: valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571
|
||||||
|
user: "999:1000"
|
||||||
|
command: [valkey-server, /etc/lab.conf]
|
||||||
|
network_mode: service:broker
|
||||||
|
depends_on: [broker]
|
||||||
|
mem_limit: 256m
|
||||||
|
volumes:
|
||||||
|
- brokerdata:/data
|
||||||
|
- ./secrets/acl/broker:/run/lab-acl/broker:ro
|
||||||
|
- ./infra/valkey-broker.conf:/etc/lab.conf:ro
|
||||||
|
|
||||||
|
openbao:
|
||||||
|
<<: *stateful
|
||||||
|
image: openbao/openbao:2.7.3@sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9
|
||||||
|
entrypoint: [bao]
|
||||||
|
command: [server, -config=/etc/lab.hcl]
|
||||||
|
user: "100:1000"
|
||||||
|
networks: [default, edge]
|
||||||
|
ports: ["127.0.0.1:${BAO_PORT:-8200}:8200"]
|
||||||
|
volumes:
|
||||||
|
- bao-data:/openbao/file
|
||||||
|
- ./secrets/tls/openbao:/run/lab-tls:ro
|
||||||
|
- ./infra/openbao/server.hcl:/etc/lab.hcl:ro
|
||||||
|
|
||||||
|
migrate:
|
||||||
|
<<: *app
|
||||||
|
command: [migrate]
|
||||||
|
restart: "no"
|
||||||
|
environment: {DATABASE_URL_FILE: /run/secrets/migrate_url}
|
||||||
|
depends_on:
|
||||||
|
db: {condition: service_healthy}
|
||||||
|
volumes:
|
||||||
|
- ./secrets/ca.crt:/run/lab-tls/ca.crt:ro
|
||||||
|
- ./secrets/migrate_url:/run/secrets/migrate_url:ro
|
||||||
|
|
||||||
|
api:
|
||||||
|
<<: *app
|
||||||
|
deploy:
|
||||||
|
replicas: 2
|
||||||
|
environment:
|
||||||
|
<<: *app-env
|
||||||
|
LAB_SERVER_TLS_DIR: /run/lab-server
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
|
GOMEMLIMIT: 256MiB
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/api-client:/run/lab-tls:ro
|
||||||
|
- ./secrets/tls/api-server:/run/lab-server:ro
|
||||||
|
- ./secrets/revocation:/run/lab-revocation:ro
|
||||||
|
depends_on:
|
||||||
|
migrate: {condition: service_completed_successfully}
|
||||||
|
s3-init: {condition: service_completed_successfully}
|
||||||
|
valkey: {condition: service_started}
|
||||||
|
openbao: {condition: service_started}
|
||||||
|
|
||||||
|
dispatcher:
|
||||||
|
<<: *app
|
||||||
|
command: [dispatcher]
|
||||||
|
environment:
|
||||||
|
<<: *app-env
|
||||||
|
DB_POOL_MAX: 4
|
||||||
|
mem_limit: 192m
|
||||||
|
cpus: 0.5
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/dispatcher-client:/run/lab-tls:ro
|
||||||
|
depends_on:
|
||||||
|
migrate: {condition: service_completed_successfully}
|
||||||
|
s3-init: {condition: service_completed_successfully}
|
||||||
|
broker-store: {condition: service_started}
|
||||||
|
openbao: {condition: service_started}
|
||||||
|
|
||||||
|
worker:
|
||||||
|
<<: *app
|
||||||
|
image: mtusi-messenger-worker:lab7
|
||||||
|
build: {context: ., target: worker}
|
||||||
|
command: [worker]
|
||||||
|
environment:
|
||||||
|
<<: *app-env
|
||||||
|
DB_POOL_MAX: 4
|
||||||
|
JOB_TIMEOUT_SECONDS: 30
|
||||||
|
WORKER_CONCURRENCY: 1
|
||||||
|
pids_limit: 64
|
||||||
|
mem_limit: 640m
|
||||||
|
cpus: 1.0
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/worker-client:/run/lab-tls:ro
|
||||||
|
depends_on:
|
||||||
|
migrate: {condition: service_completed_successfully}
|
||||||
|
s3-init: {condition: service_completed_successfully}
|
||||||
|
broker-store: {condition: service_started}
|
||||||
|
openbao: {condition: service_started}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
<<: *app
|
||||||
|
profiles: [operator]
|
||||||
|
command: [jobs, failed]
|
||||||
|
restart: "no"
|
||||||
|
environment: {BAO_ADDR: "https://openbao:8200"}
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/jobs-client:/run/lab-tls:ro
|
||||||
|
|
||||||
|
minio:
|
||||||
|
<<: *stateful
|
||||||
|
image: mtusi-minio:lab7
|
||||||
|
build: {context: ., dockerfile: Dockerfile.minio}
|
||||||
|
command: [server, /data, --console-address, "127.0.0.1:9001", --certs-dir, /run/minio]
|
||||||
|
environment:
|
||||||
|
MINIO_ROOT_USER_FILE: /run/secrets/s3_root_user
|
||||||
|
MINIO_ROOT_PASSWORD_FILE: /run/secrets/s3_root_password
|
||||||
|
MINIO_BROWSER: "off"
|
||||||
|
networks: [object_store]
|
||||||
|
mem_limit: 1g
|
||||||
|
cpus: 1.0
|
||||||
|
volumes:
|
||||||
|
- objects:/data
|
||||||
|
- ./secrets/s3_root_user:/run/secrets/s3_root_user:ro
|
||||||
|
- ./secrets/s3_root_password:/run/secrets/s3_root_password:ro
|
||||||
|
- ./secrets/tls/minio:/run/minio:ro
|
||||||
|
|
||||||
|
s3:
|
||||||
|
<<: *gateway
|
||||||
|
command: [gateway, s3]
|
||||||
|
networks: [default, object_store]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/s3:/run/lab-tls:ro
|
||||||
|
depends_on: [minio]
|
||||||
|
|
||||||
|
s3-init:
|
||||||
|
<<: *hardening
|
||||||
|
image: mtusi-minio-tools:lab7
|
||||||
|
build: {context: ., dockerfile: Dockerfile.minio, target: tools}
|
||||||
|
entrypoint: [/bin/sh, /bootstrap/s3-init.sh]
|
||||||
|
depends_on: [s3]
|
||||||
|
mem_limit: 96m
|
||||||
|
cpus: 0.5
|
||||||
|
tmpfs: ["/tmp:size=16m,mode=1777,noexec,nosuid,nodev"]
|
||||||
|
environment: {MC_CONFIG_DIR: /tmp/mc, SSL_CERT_FILE: /run/lab-ca/ca.crt}
|
||||||
|
volumes:
|
||||||
|
- ./infra:/bootstrap:ro
|
||||||
|
- ./secrets/ca.crt:/run/lab-ca/ca.crt:ro
|
||||||
|
- ./secrets/s3_root_user:/run/secrets/s3_root_user:ro
|
||||||
|
- ./secrets/s3_root_password:/run/secrets/s3_root_password:ro
|
||||||
|
- ./secrets/s3-setup:/run/s3-setup:ro
|
||||||
|
|
||||||
|
lb:
|
||||||
|
<<: *hardening
|
||||||
|
image: haproxy:3.2.6-alpine
|
||||||
|
user: "99:99"
|
||||||
|
networks: [default, edge]
|
||||||
|
ports: ["127.0.0.1:${APP_PORT:-8443}:8443"]
|
||||||
|
mem_limit: 128m
|
||||||
|
cpus: 0.5
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||||
|
- ./secrets/tls/ingress:/run/ingress:ro
|
||||||
|
- ./secrets/tls/lb-client:/run/client:ro
|
||||||
|
|
||||||
|
otel-collector:
|
||||||
|
<<: *gateway
|
||||||
|
command: [gateway, collector]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/collector:/run/lab-tls:ro
|
||||||
|
- ./secrets/revocation:/run/lab-revocation:ro
|
||||||
|
|
||||||
|
collector-engine:
|
||||||
|
<<: *stateful
|
||||||
|
image: otel/opentelemetry-collector-contrib:0.133.0
|
||||||
|
network_mode: service:otel-collector
|
||||||
|
depends_on: [otel-collector]
|
||||||
|
command: [--config=/etc/otelcol/config.yaml]
|
||||||
|
environment: {GOMEMLIMIT: 110MiB}
|
||||||
|
mem_limit: 180m
|
||||||
|
cpus: 0.5
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/collector.yaml:/etc/otelcol/config.yaml:ro
|
||||||
|
- ./secrets/tls/collector-client:/run/lab-tls:ro
|
||||||
|
|
||||||
|
prometheus:
|
||||||
|
<<: *gateway
|
||||||
|
command: [gateway, prometheus]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/prometheus:/run/lab-tls:ro
|
||||||
|
- ./secrets/revocation:/run/lab-revocation:ro
|
||||||
|
|
||||||
|
prometheus-engine:
|
||||||
|
<<: *stateful
|
||||||
|
image: prom/prometheus:v3.5.0
|
||||||
|
network_mode: service:prometheus
|
||||||
|
depends_on: [prometheus]
|
||||||
|
command: [--config.file=/etc/prometheus/prometheus.yml, --storage.tsdb.path=/prometheus,
|
||||||
|
--storage.tsdb.retention.time=7d, --storage.tsdb.retention.size=512MB, --web.enable-otlp-receiver,
|
||||||
|
"--web.listen-address=127.0.0.1:19090"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||||
|
- ./infra/otel/alerts.yml:/etc/prometheus/alerts.yml:ro
|
||||||
|
- ./secrets/tls/prometheus-client:/run/lab-tls:ro
|
||||||
|
- metrics:/prometheus
|
||||||
|
|
||||||
|
loki:
|
||||||
|
<<: *gateway
|
||||||
|
command: [gateway, loki]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/loki:/run/lab-tls:ro
|
||||||
|
- ./secrets/revocation:/run/lab-revocation:ro
|
||||||
|
|
||||||
|
loki-engine:
|
||||||
|
<<: *stateful
|
||||||
|
image: grafana/loki:3.5.3
|
||||||
|
network_mode: service:loki
|
||||||
|
depends_on: [loki]
|
||||||
|
command: [-config.file=/etc/loki/lab.yml]
|
||||||
|
volumes: [./infra/otel/loki.yml:/etc/loki/lab.yml:ro, "logs:/loki"]
|
||||||
|
|
||||||
|
tempo:
|
||||||
|
<<: *gateway
|
||||||
|
command: [gateway, tempo]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/tempo:/run/lab-tls:ro
|
||||||
|
- ./secrets/revocation:/run/lab-revocation:ro
|
||||||
|
|
||||||
|
tempo-engine:
|
||||||
|
<<: *stateful
|
||||||
|
image: grafana/tempo:2.8.2
|
||||||
|
network_mode: service:tempo
|
||||||
|
depends_on: [tempo]
|
||||||
|
command: [-config.file=/etc/tempo/lab.yml]
|
||||||
|
volumes: [./infra/otel/tempo.yml:/etc/tempo/lab.yml:ro, "traces:/var/tempo"]
|
||||||
|
|
||||||
|
grafana:
|
||||||
|
<<: *stateful
|
||||||
|
image: grafana/grafana:12.1.1
|
||||||
|
environment:
|
||||||
|
GF_AUTH_ANONYMOUS_ENABLED: "false"
|
||||||
|
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_password
|
||||||
|
GF_SECURITY_COOKIE_SECURE: "true"
|
||||||
|
GF_SERVER_PROTOCOL: https
|
||||||
|
GF_SERVER_HTTP_PORT: 3443
|
||||||
|
GF_SERVER_CERT_FILE: /run/lab-tls/tls.crt
|
||||||
|
GF_SERVER_CERT_KEY: /run/lab-tls/tls.key
|
||||||
|
GF_ANALYTICS_REPORTING_ENABLED: "false"
|
||||||
|
GF_ANALYTICS_CHECK_FOR_UPDATES: "false"
|
||||||
|
GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES: "false"
|
||||||
|
GF_PLUGINS_PREINSTALL_DISABLED: "true"
|
||||||
|
networks: [default, edge]
|
||||||
|
ports: ["127.0.0.1:${GRAFANA_PORT:-3443}:3443"]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/grafana:/run/lab-tls:ro
|
||||||
|
- ./secrets/grafana_password:/run/secrets/grafana_password:ro
|
||||||
|
- ./secrets/grafana/datasources:/etc/grafana/provisioning/datasources:ro
|
||||||
|
- ./infra/otel/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro
|
||||||
|
- ./infra/otel/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||||
|
- dashboards:/var/lib/grafana
|
||||||
|
|
||||||
|
audit:
|
||||||
|
<<: *app
|
||||||
|
profiles: [audit]
|
||||||
|
restart: "no"
|
||||||
|
command: [security-probe, matrix]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tls/audit-client:/run/lab-tls:ro
|
||||||
|
- ./secrets/audit:/audit:ro
|
||||||
|
|
||||||
|
networks:
|
||||||
|
default: {internal: true}
|
||||||
|
object_store: {internal: true}
|
||||||
|
edge: {}
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
pgdata:
|
||||||
|
sessions:
|
||||||
|
brokerdata:
|
||||||
|
bao-data:
|
||||||
|
objects:
|
||||||
|
metrics:
|
||||||
|
logs:
|
||||||
|
traces:
|
||||||
|
dashboards:
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
Lab7 verification, 2026-11-27. Docker Engine 29.3.0 (Linux/amd64), 12 vCPUs, 3.68 GiB memory assigned, i5-12450H.
|
||||||
|
Clean source copy, separate Compose project and volumes, fresh operator PKI. Verified external API: https://127.0.0.1:18443.
|
||||||
|
Public Python entry points run directly on Windows. Values and failed development attempts omitted.
|
||||||
|
|
||||||
|
> Public contract check
|
||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
|
|
||||||
|
> Public full OpenAPI validation
|
||||||
|
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||||
|
|
||||||
|
> Public HTTPS smoke
|
||||||
|
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
|
||||||
|
> Public TLS trust
|
||||||
|
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||||
|
|
||||||
|
> Student TLS, OpenBao, app ACL and telemetry
|
||||||
|
Ingress: verified CA works; mismatched external hostname rejected
|
||||||
|
API mTLS: 2 replicas allow LB; missing, foreign CA, wrong identity and wrong server SAN rejected
|
||||||
|
Broker and Collector: missing, foreign CA and wrong same-CA identity rejected
|
||||||
|
Telemetry storage: audit read succeeds; LB peer and reader ingest rejected
|
||||||
|
OpenBao: 4 scoped roles with 45s tokens; cross-role reads, policy writes and wrong same-CA identity denied
|
||||||
|
Login limit: 6 attempts across 2 replicas; attempt 7 received 429 with Retry-After
|
||||||
|
HTTP ACL: forged identity, outsider metadata/content and cross-chat attachment denied; size limit and logout passed
|
||||||
|
Telemetry: Grafana auth, mTLS data sources, API metrics, Loki request id and corresponding Tempo trace verified
|
||||||
|
Sampled traces, logs and service output contain no synthetic session/password or OpenBao root token
|
||||||
|
|
||||||
|
> Session TTL
|
||||||
|
Session expiry: valid before configured TTL and rejected after expiry
|
||||||
|
|
||||||
|
> Public persistence
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
Restart confirmed with new StartedAt on 15 containers, original container IDs and volumes retained.
|
||||||
|
|
||||||
|
> Public failover run 1
|
||||||
|
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
{"observed_instances_before": 2, "successful_writes": 116, "failed_attempts": 4, "first_recovery_seconds": 2.485}
|
||||||
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
|
||||||
|
> Public failover run 2
|
||||||
|
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
{"observed_instances_before": 2, "successful_writes": 84, "failed_attempts": 2, "first_recovery_seconds": 3.831}
|
||||||
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
|
||||||
|
> Public failover run 3
|
||||||
|
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
{"observed_instances_before": 2, "successful_writes": 99, "failed_attempts": 3, "first_recovery_seconds": 3.065}
|
||||||
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
|
||||||
|
> Public failover run 4
|
||||||
|
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
{"observed_instances_before": 2, "successful_writes": 97, "failed_attempts": 2, "first_recovery_seconds": 2.858}
|
||||||
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
|
||||||
|
> Explicit sequential failover
|
||||||
|
Sequential failover: both explicit API targets stopped, 10 writes on the respective survivor, history and session preserved
|
||||||
|
|
||||||
|
> OpenBao seal and lease expiry
|
||||||
|
Sealed OpenBao: last lease expired; verified HTTPS returned 503 after 41.51s
|
||||||
|
OpenBao unsealed by operator.
|
||||||
|
HTTPS readiness restored in 1.91s after unseal
|
||||||
|
|
||||||
|
> Track 1 worker: run 1
|
||||||
|
Worker DB: TLS and job read allowed; password hashes, messages, job deletion and owner changes denied
|
||||||
|
Worker S3: staged originals readable before cleanup
|
||||||
|
Worker S3: result reads allowed; bucket listing, staging write and delete denied
|
||||||
|
Worker queue: broker login allowed; producer, unrelated stream and admin commands denied
|
||||||
|
Worker Collector: OTLP ingest allowed
|
||||||
|
Prior worker KV policy removed; probe token revoked or already expired.
|
||||||
|
Old worker token rejected on KV read (403).
|
||||||
|
Old worker certificate denied for OpenBao login (400).
|
||||||
|
Old worker: DB password, S3 credentials and broker/Collector certificate rejected on fresh connections
|
||||||
|
New worker certificate, DB password and S3 key activated without rebuilding.
|
||||||
|
{"accept_plus_message_ms": [49.4, 50.0, 54.4, 54.7, 71.4, 72.5, 75.4, 90.7, 93.1, 100.0], "accepted": 10, "accepted_per_second": 15.35, "activation_to_all_ready_s": 1.77, "lost": 0, "p50_ms": 71.4, "p95_ms": 100.0, "p99_ms": 100.0, "parallel_uploads": 2, "ready": 10, "rotation_s": 5.4, "worker_stop_to_all_ready_s": 9.59}
|
||||||
|
|
||||||
|
> Track 1 worker: run 2
|
||||||
|
Worker DB: TLS and job read allowed; password hashes, messages, job deletion and owner changes denied
|
||||||
|
Worker S3: staged originals readable before cleanup
|
||||||
|
Worker S3: result reads allowed; bucket listing, staging write and delete denied
|
||||||
|
Worker queue: broker login allowed; producer, unrelated stream and admin commands denied
|
||||||
|
Worker Collector: OTLP ingest allowed
|
||||||
|
Prior worker KV policy removed; probe token revoked or already expired.
|
||||||
|
Old worker token rejected on KV read (403).
|
||||||
|
Old worker certificate denied for OpenBao login (400).
|
||||||
|
Old worker: DB password, S3 credentials and broker/Collector certificate rejected on fresh connections
|
||||||
|
New worker certificate, DB password and S3 key activated without rebuilding.
|
||||||
|
{"accept_plus_message_ms": [39.0, 39.4, 40.7, 46.2, 48.3, 50.2, 56.4, 61.3, 67.8, 74.9], "accepted": 10, "accepted_per_second": 34.41, "activation_to_all_ready_s": 1.78, "lost": 0, "p50_ms": 48.3, "p95_ms": 74.9, "p99_ms": 74.9, "parallel_uploads": 2, "ready": 10, "rotation_s": 6.19, "worker_stop_to_all_ready_s": 9.23}
|
||||||
|
|
||||||
|
> Final image track control
|
||||||
|
Worker DB: TLS and job read allowed; password hashes, messages, job deletion and owner changes denied
|
||||||
|
Worker S3: staged originals readable before cleanup
|
||||||
|
Worker S3: result reads allowed; bucket listing, staging write and delete denied
|
||||||
|
Worker queue: broker login allowed; producer, unrelated stream and admin commands denied
|
||||||
|
Worker Collector: OTLP ingest allowed
|
||||||
|
Prior worker KV policy removed; probe token revoked or already expired.
|
||||||
|
Old worker token rejected on KV read (403).
|
||||||
|
Old worker certificate denied for OpenBao login (400).
|
||||||
|
Old worker: DB password, S3 credentials and broker/Collector certificate rejected on fresh connections
|
||||||
|
New worker certificate, DB password and S3 key activated without rebuilding.
|
||||||
|
{"accept_plus_message_ms": [60.9, 64.0, 64.2, 68.2, 69.6, 75.1, 75.9, 92.0, 141.4, 153.5], "accepted": 10, "accepted_per_second": 20.79, "activation_to_all_ready_s": 3.41, "lost": 0, "p50_ms": 69.6, "p95_ms": 153.5, "p99_ms": 153.5, "parallel_uploads": 2, "ready": 10, "rotation_s": 21.1, "worker_stop_to_all_ready_s": 27.01}
|
||||||
|
|
||||||
|
> Compose hardening and spot resource snapshot
|
||||||
|
22 Compose service definitions checked. Read-only, no-new-privileges, and all capabilities dropped before any explicit DB bootstrap exceptions. No privileged, host networking, or Docker socket. Only LB, Grafana and OpenBao use localhost port publication.
|
||||||
|
After an auth sample: API 154.3 MiB / 512 MiB and 151.2 MiB / 512 MiB, worker 32.27 MiB / 640 MiB. CPU snapshot 0.81%, 0.88% and 0.07% respectively.
|
||||||
|
|
||||||
|
> Argon benchmark, GOMAXPROCS=1, 8 iterations per sample
|
||||||
|
19 MiB t=2: 23.726, 19.587, 19.678 ms/op; 19,925,232 B/op.
|
||||||
|
64 MiB t=3: 127.292, 122.399, 128.872 ms/op; 67,111,408 B/op.
|
||||||
|
Go tests and vet passed.
|
||||||
|
|
||||||
|
> govulncheck -mode binary on final API image
|
||||||
|
No vulnerabilities found.
|
||||||
|
|
||||||
|
> Offline Trivy, api-published
|
||||||
|
0 total, 0 critical and 0 high. See security/SCANS.md for applicability.
|
||||||
|
|
||||||
|
> Offline Trivy, worker-published
|
||||||
|
292 total, 2 critical and 49 high. See security/SCANS.md for applicability.
|
||||||
|
|
||||||
|
> Offline Trivy, bao-final
|
||||||
|
19 total, 0 critical and 2 high. See security/SCANS.md for applicability.
|
||||||
|
|
||||||
|
> Offline Trivy, haproxy
|
||||||
|
127 total, 3 critical and 28 high. See security/SCANS.md for applicability.
|
||||||
|
|
||||||
|
> Offline Trivy, collector
|
||||||
|
168 total, 7 critical and 73 high. See security/SCANS.md for applicability.
|
||||||
|
|
||||||
|
> Offline Trivy, minio
|
||||||
|
84 total, 6 critical and 43 high. See security/SCANS.md for applicability.
|
||||||
+211
@@ -0,0 +1,211 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httputil"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"regexp"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type gatewayRoute struct {
|
||||||
|
method string
|
||||||
|
path string
|
||||||
|
target string
|
||||||
|
prefix bool
|
||||||
|
identity []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func gateway(mode string) error {
|
||||||
|
const reads = "GET"
|
||||||
|
const writes = "POST"
|
||||||
|
readers := []string{"grafana-client", "audit-client"}
|
||||||
|
exporters := []string{"collector-client"}
|
||||||
|
ingest := []string{"api-client", "dispatcher-client", "worker-client"}
|
||||||
|
switch mode {
|
||||||
|
case "broker":
|
||||||
|
done := make(chan error, 2)
|
||||||
|
go func() { done <- brokerGate(":6379", "dispatcher-client") }()
|
||||||
|
go func() { done <- brokerGate(":6380", "worker-client") }()
|
||||||
|
return <-done
|
||||||
|
case "collector":
|
||||||
|
return httpGate(":4318", []string{"api-client", "dispatcher-client", "worker-client", "prometheus-client"}, []gatewayRoute{
|
||||||
|
{writes, "/v1/metrics", "http://127.0.0.1:14318", false, ingest},
|
||||||
|
{writes, "/v1/logs", "http://127.0.0.1:14318", false, ingest},
|
||||||
|
{writes, "/v1/traces", "http://127.0.0.1:14318", false, ingest},
|
||||||
|
{reads, "/metrics", "http://127.0.0.1:8888", false, []string{"prometheus-client"}},
|
||||||
|
})
|
||||||
|
case "prometheus":
|
||||||
|
return httpGate(":9090", append(readers, exporters...), []gatewayRoute{
|
||||||
|
{writes, "/api/v1/otlp/v1/metrics", "http://127.0.0.1:19090", false, exporters},
|
||||||
|
{reads, "/", "http://127.0.0.1:19090", true, readers},
|
||||||
|
{writes, "/api/v1/query", "http://127.0.0.1:19090", false, readers},
|
||||||
|
{writes, "/api/v1/query_range", "http://127.0.0.1:19090", false, readers},
|
||||||
|
{writes, "/api/v1/series", "http://127.0.0.1:19090", false, readers},
|
||||||
|
{writes, "/api/v1/labels", "http://127.0.0.1:19090", false, readers},
|
||||||
|
})
|
||||||
|
case "loki":
|
||||||
|
return httpGate(":3100", append(readers, exporters...), []gatewayRoute{
|
||||||
|
{writes, "/otlp/v1/logs", "http://127.0.0.1:13100", false, exporters},
|
||||||
|
{reads, "/loki/api/v1/", "http://127.0.0.1:13100", true, readers},
|
||||||
|
{reads, "/ready", "http://127.0.0.1:13100", false, readers},
|
||||||
|
})
|
||||||
|
case "tempo":
|
||||||
|
return httpGate(":3200", append(readers, exporters...), []gatewayRoute{
|
||||||
|
{writes, "/v1/traces", "http://127.0.0.1:14318", false, exporters},
|
||||||
|
{reads, "/api/", "http://127.0.0.1:13200", true, readers},
|
||||||
|
{reads, "/ready", "http://127.0.0.1:13200", false, readers},
|
||||||
|
})
|
||||||
|
case "s3":
|
||||||
|
return httpGate(":9000", nil, []gatewayRoute{{"", "/", "https://minio:9000", true, nil}})
|
||||||
|
default:
|
||||||
|
return errors.New("invalid gateway role")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var s3Select = regexp.MustCompile(`(?i)(^|&)select([=&]|$)`)
|
||||||
|
|
||||||
|
func blockedS3(r *http.Request) bool {
|
||||||
|
for _, prefix := range []string{"/minio/storage", "/minio/peer", "/minio/grid", "/minio/bootstrap"} {
|
||||||
|
if strings.HasPrefix(strings.ToLower(r.URL.Path), prefix) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
query, err := url.QueryUnescape(r.URL.RawQuery)
|
||||||
|
return err != nil || s3Select.MatchString(query) ||
|
||||||
|
strings.EqualFold(r.Header.Get("X-Amz-Content-Sha256"), "STREAMING-UNSIGNED-PAYLOAD-TRAILER") ||
|
||||||
|
len(r.Header.Values("X-Minio-Source-Replication-Request")) != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func httpGate(bind string, allowed []string, routes []gatewayRoute) error {
|
||||||
|
cfg, err := serverTLS(allowed)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
proxies := make(map[string]*httputil.ReverseProxy)
|
||||||
|
transport, err := labHTTPTransport(false)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, route := range routes {
|
||||||
|
target, e := url.Parse(route.target)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
proxy := &httputil.ReverseProxy{
|
||||||
|
Transport: transport,
|
||||||
|
Rewrite: func(request *httputil.ProxyRequest) {
|
||||||
|
request.SetURL(target)
|
||||||
|
request.Out.Host = request.In.Host
|
||||||
|
// S3 signatures cover the original query and Host.
|
||||||
|
if len(allowed) == 0 {
|
||||||
|
request.Out.URL.RawQuery = request.In.URL.RawQuery
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) {
|
||||||
|
http.Error(w, "backend unavailable", http.StatusBadGateway)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
proxies[route.target] = proxy
|
||||||
|
}
|
||||||
|
server := &http.Server{
|
||||||
|
Addr: bind, TLSConfig: cfg, ReadHeaderTimeout: 3 * time.Second,
|
||||||
|
ReadTimeout: 35 * time.Second, WriteTimeout: 40 * time.Second, IdleTimeout: 10 * time.Second,
|
||||||
|
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var identity string
|
||||||
|
if len(allowed) > 0 {
|
||||||
|
peer := r.TLS.PeerCertificates[0]
|
||||||
|
if trustedPeer(peer) != nil {
|
||||||
|
http.Error(w, "client certificate denied", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
identity = clientIdentity(peer)
|
||||||
|
} else if blockedS3(r) {
|
||||||
|
http.Error(w, "operation denied", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, route := range routes {
|
||||||
|
pathMatch := r.URL.Path == route.path || route.prefix && strings.HasPrefix(r.URL.Path, route.path)
|
||||||
|
if pathMatch && (route.method == "" || r.Method == route.method) &&
|
||||||
|
(len(route.identity) == 0 || slices.Contains(route.identity, identity)) {
|
||||||
|
proxies[route.target].ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
http.Error(w, "operation denied", http.StatusForbidden)
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
return server.ListenAndServeTLS("", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
func brokerGate(address, identity string) error {
|
||||||
|
cfg, err := serverTLS([]string{identity})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
listener, err := tls.Listen("tcp", address, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer listener.Close()
|
||||||
|
slots := make(chan struct{}, 64)
|
||||||
|
for {
|
||||||
|
conn, err := listener.Accept()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case slots <- struct{}{}:
|
||||||
|
go func() {
|
||||||
|
defer func() { <-slots }()
|
||||||
|
forwardBroker(conn.(*tls.Conn))
|
||||||
|
}()
|
||||||
|
default:
|
||||||
|
conn.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func forwardBroker(client *tls.Conn) {
|
||||||
|
defer client.Close()
|
||||||
|
_ = client.SetDeadline(time.Now().Add(3 * time.Second))
|
||||||
|
if client.Handshake() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = client.SetDeadline(time.Time{})
|
||||||
|
backend, err := net.DialTimeout("tcp", "127.0.0.1:16379", time.Second)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer backend.Close()
|
||||||
|
peer := client.ConnectionState().PeerCertificates[0]
|
||||||
|
done := make(chan struct{}, 2)
|
||||||
|
go func() { _, _ = io.Copy(backend, client); done <- struct{}{} }()
|
||||||
|
go func() { _, _ = io.Copy(client, backend); done <- struct{}{} }()
|
||||||
|
check := time.NewTicker(time.Second)
|
||||||
|
defer check.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
return
|
||||||
|
case <-check.C:
|
||||||
|
if trustedPeer(peer) != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func gatewayCommand() error {
|
||||||
|
if len(os.Args) != 3 {
|
||||||
|
return errors.New("gateway requires a role")
|
||||||
|
}
|
||||||
|
return gateway(os.Args[2])
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
module mtusi-messenger
|
||||||
|
|
||||||
|
go 1.26.0
|
||||||
|
|
||||||
|
toolchain go1.27.4
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/jackc/pgx/v5 v5.13.0
|
||||||
|
github.com/minio/minio-go/v7 v7.4.1
|
||||||
|
github.com/redis/go-redis/v9 v9.24.1
|
||||||
|
go.opentelemetry.io/otel v1.47.0
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0
|
||||||
|
go.opentelemetry.io/otel/log v1.47.0
|
||||||
|
go.opentelemetry.io/otel/metric v1.47.0
|
||||||
|
go.opentelemetry.io/otel/sdk v1.47.0
|
||||||
|
go.opentelemetry.io/otel/sdk/log v1.47.0
|
||||||
|
go.opentelemetry.io/otel/sdk/metric v1.47.0
|
||||||
|
go.opentelemetry.io/otel/trace v1.47.0
|
||||||
|
golang.org/x/crypto v0.59.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
|
github.com/go-logr/logr v1.4.4 // indirect
|
||||||
|
github.com/go-logr/stdr v1.2.2 // indirect
|
||||||
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
||||||
|
github.com/klauspost/compress v1.20.2 // indirect
|
||||||
|
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||||
|
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||||
|
github.com/minio/crc64nvme v1.1.1 // 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.6.4 // indirect
|
||||||
|
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||||
|
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
|
||||||
|
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
|
||||||
|
go.uber.org/atomic v1.12.0 // indirect
|
||||||
|
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||||
|
golang.org/x/net v0.63.0 // indirect
|
||||||
|
golang.org/x/sync v0.25.0 // indirect
|
||||||
|
golang.org/x/sys v0.50.0 // indirect
|
||||||
|
golang.org/x/text v0.44.0 // indirect
|
||||||
|
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc // indirect
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect
|
||||||
|
google.golang.org/grpc v1.83.2 // indirect
|
||||||
|
google.golang.org/protobuf v1.36.12 // indirect
|
||||||
|
gopkg.in/ini.v1 v1.67.3 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
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/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
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-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||||
|
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||||
|
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||||
|
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||||
|
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||||
|
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||||
|
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||||
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
|
||||||
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
||||||
|
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo=
|
||||||
|
github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||||
|
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
|
||||||
|
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
|
||||||
|
github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI=
|
||||||
|
github.com/minio/crc64nvme v1.1.1/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.4.1 h1:PtU/zIOfQRWZ+QydXAZysc+xZYHdG+BBR4Z6TUvy73w=
|
||||||
|
github.com/minio/minio-go/v7 v7.4.1/go.mod h1:nQnQi7zTfXR4lREtYXZQWqo5aw0Rqv+ZqCGrTORygRk=
|
||||||
|
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||||
|
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/redis/go-redis/v9 v9.24.1 h1:WZ9a1QO2mkLFLYyQ1IPFvS4xBuCuZy9eXtIxppdj/Z0=
|
||||||
|
github.com/redis/go-redis/v9 v9.24.1/go.mod h1:ted97kpLnB4S2KJkTkw+7GzRjgkFnU909IIrksu+ut4=
|
||||||
|
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/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
|
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||||
|
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.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||||
|
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||||
|
github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ=
|
||||||
|
github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||||
|
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
|
||||||
|
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
|
||||||
|
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||||
|
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||||
|
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.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||||
|
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 h1:5WVp40k2fJHuc5BtNTgKk+EugKFT8Eg3lywFfCPI/nE=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0/go.mod h1:59nH0RYCGHRlwt15WyioeSYINBbuObeBpTowPhEKWHY=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0 h1:7kszRN4Ze5GeAkUnBjBSUIunVBMA+mZIG04auueqguM=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0/go.mod h1:CLzakYy8jOdkBfcveCWYkeKJxujcF4xPhh2Z7IfE98U=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
|
||||||
|
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
|
||||||
|
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
|
||||||
|
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
|
||||||
|
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
|
||||||
|
go.opentelemetry.io/otel/metric/x v0.69.0 h1:DjRLr15H83v+hCW7JA9NoJvOkYTtmq5YoDRbe9deYpM=
|
||||||
|
go.opentelemetry.io/otel/metric/x v0.69.0/go.mod h1:uVvsMPMFFyj/HUQfrUnH3JjnOQ1dwFDorgFLRBasM0k=
|
||||||
|
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
|
||||||
|
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
|
||||||
|
go.opentelemetry.io/otel/sdk/log v1.47.0 h1:W4N/ZfgpkRRnmARnqYoQ6BrWA0mrj8IzVDNLlpmUJZY=
|
||||||
|
go.opentelemetry.io/otel/sdk/log v1.47.0/go.mod h1:Wu74Z2EmOKXi2FleSNAb0Hyau2G+r5kubSEMJw5aAMs=
|
||||||
|
go.opentelemetry.io/otel/sdk/log/logtest v0.23.0 h1:j3pm42QCrKYYLLkI6OrV1QHFkUfDA6/4EP+Y1PzggLg=
|
||||||
|
go.opentelemetry.io/otel/sdk/log/logtest v0.23.0/go.mod h1:zt0gEnuTZgDvqvczHwYswz93eqMaIr6upTTsdV/HUlU=
|
||||||
|
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
|
||||||
|
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
|
||||||
|
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
|
||||||
|
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
|
||||||
|
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
|
||||||
|
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
|
||||||
|
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||||
|
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||||
|
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||||
|
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||||
|
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||||
|
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||||
|
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||||
|
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||||
|
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
||||||
|
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
||||||
|
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||||
|
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||||
|
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||||
|
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
|
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||||
|
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||||
|
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||||
|
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||||
|
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc h1:rZHRz0ogq4Pid1IKtA/ivHi8XONVF5tqUQXA2TtgpkE=
|
||||||
|
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:K/n0XLazCJHjD73YuMyNJsN38BPPy1kfFnKxUXaThFU=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||||
|
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||||
|
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||||
|
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||||
|
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw=
|
||||||
|
gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"slices"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The advisory lock serializes this key across processes. Message and result
|
||||||
|
// commit together; an interrupted/rolled-back transaction reserves nothing.
|
||||||
|
func (a *App) createMessage(ctx context.Context, chat, user, key, text string, ids []string) (Message, error) {
|
||||||
|
m := Message{ChatID: chat, SenderID: user, Text: text, AttachmentIDs: ids}
|
||||||
|
tx, err := a.db.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return m, unavailable()
|
||||||
|
}
|
||||||
|
defer tx.Rollback(ctx)
|
||||||
|
// POST and the canonical chat path are implicit in this dedicated table.
|
||||||
|
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", user+":"+chat+":"+key); err != nil {
|
||||||
|
return m, unavailable()
|
||||||
|
}
|
||||||
|
var previous Message
|
||||||
|
var created time.Time
|
||||||
|
err = tx.QueryRow(ctx, `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at,ARRAY(SELECT unnest(m.attachment_ids)::text)
|
||||||
|
FROM message_keys k JOIN messages m ON m.id=k.message_id
|
||||||
|
WHERE k.user_id=$1 AND k.chat_id=$2 AND k.key=$3 AND k.expires_at>clock_timestamp()`, user, chat, key).Scan(&previous.ID, &previous.ChatID, &previous.SenderID, utf8String{&previous.Text}, &created, &previous.AttachmentIDs)
|
||||||
|
if err == nil {
|
||||||
|
if previous.Text != text || !slices.Equal(previous.AttachmentIDs, ids) {
|
||||||
|
return m, apiError{409, "conflict", "Idempotency key has a different message"}
|
||||||
|
}
|
||||||
|
previous.CreatedAt = stamp(created)
|
||||||
|
return previous, nil
|
||||||
|
}
|
||||||
|
if !errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return m, unavailable()
|
||||||
|
}
|
||||||
|
if _, err = tx.Exec(ctx, "DELETE FROM message_keys WHERE user_id=$1 AND chat_id=$2 AND key=$3", user, chat, key); err != nil {
|
||||||
|
return m, unavailable()
|
||||||
|
}
|
||||||
|
// Serialize with attachment state transitions; stable ordering prevents cross-upload deadlocks.
|
||||||
|
locked := slices.Clone(ids)
|
||||||
|
sort.Strings(locked)
|
||||||
|
for _, id := range locked {
|
||||||
|
if err = attachmentLock(ctx, tx, id); err != nil {
|
||||||
|
return m, unavailable()
|
||||||
|
}
|
||||||
|
var missingSince *time.Time
|
||||||
|
var status string
|
||||||
|
err = tx.QueryRow(ctx, "SELECT missing_since,status FROM attachments WHERE id=$1 AND chat_id=$2", id, chat).Scan(&missingSince, &status)
|
||||||
|
if err != nil {
|
||||||
|
return m, dbError(err)
|
||||||
|
}
|
||||||
|
if status == "failed" {
|
||||||
|
return m, apiError{409, "conflict", "Attachment processing failed"}
|
||||||
|
}
|
||||||
|
if missingSince != nil {
|
||||||
|
return m, unavailable()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m.ID = uuid()
|
||||||
|
if err = tx.QueryRow(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,attachment_ids) VALUES($1,$2,$3,$4,$5) RETURNING created_at", m.ID, chat, user, []byte(text), ids).Scan(&created); err != nil {
|
||||||
|
return m, dbError(err)
|
||||||
|
}
|
||||||
|
if _, err = tx.Exec(ctx, "INSERT INTO message_keys(user_id,chat_id,key,message_id,expires_at) VALUES($1,$2,$3,$4,clock_timestamp()+$5::bigint*interval '1 second')", user, chat, key, m.ID, int64(a.idempotencyTTL.Seconds())); err != nil {
|
||||||
|
return m, unavailable()
|
||||||
|
}
|
||||||
|
for _, id := range ids {
|
||||||
|
if _, err = tx.Exec(ctx, "INSERT INTO message_attachments(message_id,chat_id,attachment_id) VALUES($1,$2,$3)", m.ID, chat, id); err != nil {
|
||||||
|
return m, dbError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err = tx.Commit(ctx); err != nil {
|
||||||
|
return m, unavailable()
|
||||||
|
}
|
||||||
|
m.CreatedAt = stamp(created)
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/minio/minio-go/v7"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (a *App) cleanStaging(ctx context.Context, retention int) error {
|
||||||
|
listCtx, cancel := context.WithCancel(ctx)
|
||||||
|
defer cancel()
|
||||||
|
for entry := range a.s3.ListObjects(listCtx, a.bucket, minio.ListObjectsOptions{Prefix: "staging/", Recursive: true}) {
|
||||||
|
if entry.Err != nil {
|
||||||
|
return entry.Err
|
||||||
|
}
|
||||||
|
id := strings.TrimPrefix(entry.Key, "staging/")
|
||||||
|
if normalized, err := normalizeID(id); err != nil || normalized != id {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := a.cleanStagedImage(ctx, id, entry.LastModified, retention); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) cleanStagedImage(ctx context.Context, id string, modified time.Time, retention int) error {
|
||||||
|
tx, err := a.db.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer rollbackAttachment(tx)
|
||||||
|
var locked bool
|
||||||
|
if err = tx.QueryRow(ctx, "SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))", "attachment:"+id).Scan(&locked); err != nil || !locked {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var removable bool
|
||||||
|
err = tx.QueryRow(ctx, `SELECT result_version>0 OR
|
||||||
|
(status='failed' AND updated_at<=clock_timestamp()-$2::bigint*interval '1 second')
|
||||||
|
FROM attachments WHERE id=$1`, id, retention).Scan(&removable)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
removable = time.Since(modified) > time.Hour
|
||||||
|
} else if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if removable {
|
||||||
|
return a.s3.RemoveObject(ctx, a.bucket, stagingKey(id), minio.RemoveObjectOptions{})
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+136
@@ -0,0 +1,136 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/minio/minio-go/v7"
|
||||||
|
)
|
||||||
|
|
||||||
|
type imageFailure string
|
||||||
|
|
||||||
|
func (e imageFailure) Error() string { return string(e) }
|
||||||
|
|
||||||
|
func (a *App) generateImage(ctx context.Context, j imageJob, src imageSource) ([]Variant, error) {
|
||||||
|
dir, err := os.MkdirTemp("", "image-job-")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(dir)
|
||||||
|
key := stagingKey(j.AttachmentID)
|
||||||
|
if j.Version == 2 {
|
||||||
|
key = resultKey(j.AttachmentID, 1, "original")
|
||||||
|
}
|
||||||
|
original := filepath.Join(dir, "input")
|
||||||
|
if err = a.fetchImage(ctx, src, key, original); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
command := exec.CommandContext(ctx, "/usr/local/bin/python3", "-I", "/pipeline.py", dir, src.contentType, strconv.Itoa(j.Version))
|
||||||
|
command.Env = []string{"LC_ALL=C.UTF-8"}
|
||||||
|
manifest, err := command.Output()
|
||||||
|
if err != nil {
|
||||||
|
var exit *exec.ExitError
|
||||||
|
if errors.As(err, &exit) && exit.ExitCode() == 2 {
|
||||||
|
return nil, imageFailure("invalid_image")
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var variants []Variant
|
||||||
|
if err = json.Unmarshal(manifest, &variants); err != nil || len(variants) != 3 {
|
||||||
|
return nil, errors.New("invalid encoder manifest")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = a.putImage(ctx, resultKey(j.AttachmentID, j.Version, "original"), original, src); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
injectImageFault("after_effect", j.AttachmentID)
|
||||||
|
for i, name := range []string{"thumbnail", "crop", "optimized"} {
|
||||||
|
v := &variants[i]
|
||||||
|
v.Name = name
|
||||||
|
v.ContentType = "image/jpeg"
|
||||||
|
if name == "optimized" {
|
||||||
|
v.ContentType = "image/webp"
|
||||||
|
}
|
||||||
|
path := filepath.Join(dir, name)
|
||||||
|
v.SizeBytes, v.SHA256, err = fileDigest(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err = a.putImage(ctx, resultKey(j.AttachmentID, j.Version, name), path, imageSource{v.ContentType, v.SizeBytes, v.SHA256}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return variants, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) fetchImage(ctx context.Context, src imageSource, key, path string) (result error) {
|
||||||
|
ctx, span := startSpan(ctx, "s3 get source")
|
||||||
|
defer func() { endSpan(span, result) }()
|
||||||
|
object, err := a.s3.GetObject(ctx, a.bucket, key, minio.GetObjectOptions{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer object.Close()
|
||||||
|
file, err := os.Create(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
digest := sha256.New()
|
||||||
|
size, err := io.Copy(io.MultiWriter(file, digest), io.LimitReader(object, maxUploadBytes+1))
|
||||||
|
closeErr := file.Close()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
return closeErr
|
||||||
|
}
|
||||||
|
if size != src.size || hex.EncodeToString(digest.Sum(nil)) != src.sha256 {
|
||||||
|
return imageFailure("source_integrity")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fileDigest(path string) (int64, string, error) {
|
||||||
|
file, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return 0, "", err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
digest := sha256.New()
|
||||||
|
size, err := io.Copy(digest, file)
|
||||||
|
return size, hex.EncodeToString(digest.Sum(nil)), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) putImage(ctx context.Context, key, path string, src imageSource) (result error) {
|
||||||
|
ctx, span := startSpan(ctx, "s3 put result")
|
||||||
|
defer func() { endSpan(span, result) }()
|
||||||
|
file, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
opts := minio.PutObjectOptions{ContentType: src.contentType, DisableMultipart: true,
|
||||||
|
UserMetadata: map[string]string{"sha256": src.sha256}}
|
||||||
|
opts.SetMatchETagExcept("*")
|
||||||
|
_, err = a.s3.PutObject(ctx, a.bucket, key, file, src.size, opts)
|
||||||
|
if minio.ToErrorResponse(err).Code != "PreconditionFailed" {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
info, err := a.s3.StatObject(ctx, a.bucket, key, minio.StatObjectOptions{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if info.Size != src.size || info.ContentType != src.contentType || info.Metadata.Get("X-Amz-Meta-Sha256") != src.sha256 {
|
||||||
|
return imageFailure("result_integrity")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+263
@@ -0,0 +1,263 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math/rand/v2"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"go.opentelemetry.io/otel/propagation"
|
||||||
|
)
|
||||||
|
|
||||||
|
type imageJob struct {
|
||||||
|
SchemaVersion int `json:"schema_version"`
|
||||||
|
JobID string `json:"job_id"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
AttachmentID string `json:"attachment_id"`
|
||||||
|
Version int `json:"pipeline_version"`
|
||||||
|
Attempt int `json:"attempt"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type imageSource struct {
|
||||||
|
contentType string
|
||||||
|
size int64
|
||||||
|
sha256 string
|
||||||
|
}
|
||||||
|
|
||||||
|
func enqueueImage(ctx context.Context, tx pgx.Tx, attachment string, version int) error {
|
||||||
|
carrier := propagation.MapCarrier{}
|
||||||
|
traceContext.Inject(ctx, carrier)
|
||||||
|
_, err := tx.Exec(ctx, `INSERT INTO image_jobs(id,attachment_id,version,traceparent,tracestate)
|
||||||
|
VALUES($1,$2,$3,$4,$5)`, uuid(), attachment, version, carrier.Get("traceparent"), carrier.Get("tracestate"))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func stagingKey(id string) string { return "staging/" + id }
|
||||||
|
|
||||||
|
func resultKey(id string, version int, variant string) string {
|
||||||
|
if version == 0 {
|
||||||
|
return "original/" + id
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s/%s/v%d", variant, id, version)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) claimImage(ctx context.Context, j imageJob, lease time.Duration) (imageSource, bool, error) {
|
||||||
|
var src imageSource
|
||||||
|
tx, err := a.db.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return src, false, err
|
||||||
|
}
|
||||||
|
defer rollbackAttachment(tx)
|
||||||
|
if err = attachmentLock(ctx, tx, j.AttachmentID); err != nil {
|
||||||
|
return src, false, err
|
||||||
|
}
|
||||||
|
tag, err := tx.Exec(ctx, `UPDATE image_jobs j SET state='processing',
|
||||||
|
lease_until=clock_timestamp()+$5::bigint*interval '1 second', updated_at=clock_timestamp()
|
||||||
|
FROM attachments a WHERE a.id=j.attachment_id AND a.active_version=j.version
|
||||||
|
AND j.id=$1 AND j.attachment_id=$2 AND j.version=$3 AND j.attempt=$4
|
||||||
|
AND j.state='queued' AND j.next_at<=clock_timestamp()`, j.JobID, j.AttachmentID, j.Version, j.Attempt, int64(lease.Seconds()))
|
||||||
|
if err != nil || tag.RowsAffected() == 0 {
|
||||||
|
return src, false, err
|
||||||
|
}
|
||||||
|
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='processing',updated_at=clock_timestamp()
|
||||||
|
WHERE id=$1 AND result_version=0`, j.AttachmentID); err != nil {
|
||||||
|
return src, false, err
|
||||||
|
}
|
||||||
|
err = tx.QueryRow(ctx, "SELECT content_type,size_bytes,sha256 FROM attachments WHERE id=$1", j.AttachmentID).
|
||||||
|
Scan(&src.contentType, &src.size, &src.sha256)
|
||||||
|
if err != nil {
|
||||||
|
return src, false, err
|
||||||
|
}
|
||||||
|
return src, true, tx.Commit(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) completeImage(ctx context.Context, j imageJob, variants []Variant) (float64, bool, error) {
|
||||||
|
tx, err := a.db.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return 0, false, err
|
||||||
|
}
|
||||||
|
defer rollbackAttachment(tx)
|
||||||
|
if err = attachmentLock(ctx, tx, j.AttachmentID); err != nil {
|
||||||
|
return 0, false, err
|
||||||
|
}
|
||||||
|
var seconds float64
|
||||||
|
err = tx.QueryRow(ctx, `UPDATE image_jobs SET state='ready',lease_until=NULL,error_code=NULL,
|
||||||
|
updated_at=clock_timestamp(),ready_at=clock_timestamp()
|
||||||
|
WHERE id=$1 AND attempt=$2 AND state='processing' AND lease_until>clock_timestamp()
|
||||||
|
RETURNING extract(epoch FROM (ready_at-created_at))::float8`, j.JobID, j.Attempt).Scan(&seconds)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return 0, false, nil // A lost lease is recovered by the dispatcher.
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return 0, false, err
|
||||||
|
}
|
||||||
|
tag, err := tx.Exec(ctx, `UPDATE attachments SET status='ready',error_code=NULL,result_version=$2,
|
||||||
|
variants=$3,updated_at=clock_timestamp() WHERE id=$1 AND active_version=$2 AND result_version<$2`,
|
||||||
|
j.AttachmentID, j.Version, variants)
|
||||||
|
if err != nil {
|
||||||
|
return 0, false, err
|
||||||
|
}
|
||||||
|
if tag.RowsAffected() != 1 {
|
||||||
|
return 0, false, errors.New("image result fence rejected")
|
||||||
|
}
|
||||||
|
if err = tx.Commit(ctx); err != nil {
|
||||||
|
return 0, false, err
|
||||||
|
}
|
||||||
|
return seconds, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) failImage(ctx context.Context, j imageJob, code string, permanent, expired bool, maxAttempts int) (string, error) {
|
||||||
|
tx, err := a.db.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer rollbackAttachment(tx)
|
||||||
|
if err = attachmentLock(ctx, tx, j.AttachmentID); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
var cycleStart int
|
||||||
|
err = tx.QueryRow(ctx, `SELECT cycle_start FROM image_jobs WHERE id=$1 AND attempt=$2
|
||||||
|
AND state='processing' AND (lease_until<=clock_timestamp())=$3 FOR UPDATE`, j.JobID, j.Attempt, expired).Scan(&cycleStart)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return "lease_lost", nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
used := j.Attempt - cycleStart + 1
|
||||||
|
state := "failed"
|
||||||
|
if !permanent {
|
||||||
|
if used >= maxAttempts {
|
||||||
|
code = "retry_exhausted"
|
||||||
|
} else {
|
||||||
|
state = "queued"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
attempt := j.Attempt
|
||||||
|
var delay int64
|
||||||
|
if state == "queued" {
|
||||||
|
attempt++
|
||||||
|
base := int64(1000) << min(used-1, 5)
|
||||||
|
delay = base + rand.Int64N(base)
|
||||||
|
}
|
||||||
|
_, err = tx.Exec(ctx, `UPDATE image_jobs SET state=$2,error_code=$3,lease_until=NULL,attempt=$4,
|
||||||
|
published=false,next_at=clock_timestamp()+$5::bigint*interval '1 millisecond',updated_at=clock_timestamp() WHERE id=$1`,
|
||||||
|
j.JobID, state, code, attempt, delay)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
var publicCode *string
|
||||||
|
if state == "failed" {
|
||||||
|
publicCode = &code
|
||||||
|
}
|
||||||
|
if _, err = tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,updated_at=clock_timestamp()
|
||||||
|
WHERE id=$1 AND active_version=$4 AND result_version=0`, j.AttachmentID, state, publicCode, j.Version); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return state, tx.Commit(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) recoverImage(ctx context.Context, maxAttempts int) error {
|
||||||
|
var j imageJob
|
||||||
|
err := a.db.QueryRow(ctx, `SELECT id::text,attachment_id::text,version,attempt FROM image_jobs
|
||||||
|
WHERE state='processing' AND lease_until<=clock_timestamp() ORDER BY lease_until LIMIT 1`).
|
||||||
|
Scan(&j.JobID, &j.AttachmentID, &j.Version, &j.Attempt)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = a.failImage(ctx, j, "lease_expired", false, true, maxAttempts)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) upgradeImage(ctx context.Context, id string) error {
|
||||||
|
tx, err := a.db.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer rollbackAttachment(tx)
|
||||||
|
if err = attachmentLock(ctx, tx, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tag, err := tx.Exec(ctx, `UPDATE attachments SET active_version=2
|
||||||
|
WHERE id=$1 AND active_version=1 AND result_version=1 AND status='ready'`, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if tag.RowsAffected() != 1 {
|
||||||
|
return errors.New("attachment is not eligible for upgrade")
|
||||||
|
}
|
||||||
|
if err = enqueueImage(ctx, tx, id, 2); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Commit(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) replayImage(ctx context.Context, id string, retention int) error {
|
||||||
|
var attachment string
|
||||||
|
if err := a.db.QueryRow(ctx, "SELECT attachment_id::text FROM image_jobs WHERE id=$1", id).Scan(&attachment); err != nil {
|
||||||
|
return errors.New("job lookup failed")
|
||||||
|
}
|
||||||
|
tx, err := a.db.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer rollbackAttachment(tx)
|
||||||
|
if err = attachmentLock(ctx, tx, attachment); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var attempt int
|
||||||
|
var code string
|
||||||
|
err = tx.QueryRow(ctx, `SELECT j.attempt,j.error_code FROM image_jobs j JOIN attachments a ON a.id=j.attachment_id
|
||||||
|
WHERE j.id=$1 AND j.state='failed' AND a.active_version=j.version AND a.result_version<j.version
|
||||||
|
AND (j.version=2 OR j.updated_at>clock_timestamp()-$2::bigint*interval '1 second')`, id, retention).Scan(&attempt, &code)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return errors.New("job is not eligible for replay")
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
attempt++
|
||||||
|
if _, err = tx.Exec(ctx, "INSERT INTO image_job_replays(job_id,attempt,previous_error) VALUES($1,$2,$3)", id, attempt, code); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err = tx.Exec(ctx, `UPDATE image_jobs SET state='queued',attempt=$2,cycle_start=$2,error_code=NULL,
|
||||||
|
published=false,next_at=clock_timestamp(),updated_at=clock_timestamp() WHERE id=$1`, id, attempt); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp()
|
||||||
|
WHERE id=$1 AND result_version=0`, attachment); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Commit(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) listFailedImages(ctx context.Context) error {
|
||||||
|
rows, err := a.db.Query(ctx, `SELECT id::text,attachment_id::text,version,attempt,error_code,updated_at FROM image_jobs
|
||||||
|
WHERE state='failed' ORDER BY updated_at DESC,id LIMIT 100`)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
out := json.NewEncoder(os.Stdout)
|
||||||
|
for rows.Next() {
|
||||||
|
var j imageJob
|
||||||
|
var code string
|
||||||
|
var updated time.Time
|
||||||
|
if err = rows.Scan(&j.JobID, &j.AttachmentID, &j.Version, &j.Attempt, &code, &updated); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err = out.Encode(map[string]any{"job_id": j.JobID, "attachment_id": j.AttachmentID,
|
||||||
|
"pipeline_version": j.Version, "attempt": j.Attempt, "error_code": code, "updated_at": stamp(updated)}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rows.Err()
|
||||||
|
}
|
||||||
+312
@@ -0,0 +1,312 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
otellog "go.opentelemetry.io/otel/log"
|
||||||
|
"go.opentelemetry.io/otel/metric"
|
||||||
|
"go.opentelemetry.io/otel/propagation"
|
||||||
|
)
|
||||||
|
|
||||||
|
const imageStream = "attachment-jobs"
|
||||||
|
const imageGroup = "image-workers"
|
||||||
|
|
||||||
|
var ackImage = redis.NewScript(`
|
||||||
|
if redis.call('XACK', KEYS[1], ARGV[1], ARGV[2]) == 1 then
|
||||||
|
redis.call('XDEL', KEYS[1], ARGV[2])
|
||||||
|
end
|
||||||
|
return 1
|
||||||
|
`)
|
||||||
|
|
||||||
|
func imageCommand(db *pgxpool.Pool, dbTrace *databaseTracer, args []string, secrets serviceSecrets) error {
|
||||||
|
a := &App{db: db}
|
||||||
|
retention := positive("STAGING_RETENTION_SECONDS", 86400)
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
if args[0] == "jobs" {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if len(args) == 2 && args[1] == "failed" {
|
||||||
|
return a.listFailedImages(ctx)
|
||||||
|
}
|
||||||
|
if len(args) != 3 {
|
||||||
|
return errors.New("usage: jobs failed | jobs replay <job-id> | jobs upgrade <attachment-id>")
|
||||||
|
}
|
||||||
|
id, err := normalizeID(args[2])
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("invalid job or attachment ID")
|
||||||
|
}
|
||||||
|
switch args[1] {
|
||||||
|
case "replay":
|
||||||
|
return a.replayImage(ctx, id, retention)
|
||||||
|
case "upgrade":
|
||||||
|
return a.upgradeImage(ctx, id)
|
||||||
|
default:
|
||||||
|
return errors.New("unknown jobs command")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(args) != 1 || (args[0] != "dispatcher" && args[0] != "worker") {
|
||||||
|
return errors.New("unknown command")
|
||||||
|
}
|
||||||
|
attempts := positive("JOB_MAX_ATTEMPTS", 5)
|
||||||
|
timeoutSeconds := positive("JOB_TIMEOUT_SECONDS", 30)
|
||||||
|
if attempts > 20 || timeoutSeconds > 120 || positive("WORKER_CONCURRENCY", 1) != 1 {
|
||||||
|
return errors.New("invalid image job limits")
|
||||||
|
}
|
||||||
|
timeout := time.Duration(timeoutSeconds) * time.Second
|
||||||
|
s3, bucket, err := s3Client(secrets)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("invalid image storage configuration")
|
||||||
|
}
|
||||||
|
a.s3, a.bucket = s3, bucket
|
||||||
|
opts, err := redisTLS(secrets.BrokerURL, true)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("invalid broker configuration")
|
||||||
|
}
|
||||||
|
opts.MaxRetries = -1
|
||||||
|
opts.PoolSize = 2
|
||||||
|
opts.DialTimeout = time.Second
|
||||||
|
opts.ReadTimeout = 2 * time.Second
|
||||||
|
opts.WriteTimeout = time.Second
|
||||||
|
opts.ContextTimeoutEnabled = true
|
||||||
|
broker := redis.NewClient(opts)
|
||||||
|
defer broker.Close()
|
||||||
|
instruments, shutdown, err := startTelemetry(args[0], db, dbTrace)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer shutdown()
|
||||||
|
a.telemetry = instruments
|
||||||
|
|
||||||
|
if args[0] == "dispatcher" {
|
||||||
|
a.dispatchImages(ctx, broker, attempts, retention)
|
||||||
|
} else {
|
||||||
|
a.consumeImages(ctx, broker, attempts, timeout)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func injectImageFault(phase, attachment string) {
|
||||||
|
if os.Getenv("LAB5_FAULT_ATTACHMENT") == attachment && os.Getenv("LAB5_FAULT") == phase {
|
||||||
|
slog.Info("test crash", "phase", phase, "attachment_id", attachment)
|
||||||
|
os.Exit(86)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) publishImage(ctx context.Context, broker *redis.Client) (published bool, result error) {
|
||||||
|
tx, err := a.db.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
defer rollbackAttachment(tx)
|
||||||
|
j := imageJob{SchemaVersion: 1, Type: "attachment.process.v1"}
|
||||||
|
var created time.Time
|
||||||
|
var parent, state string
|
||||||
|
err = tx.QueryRow(ctx, `SELECT id::text,attachment_id::text,version,attempt,created_at,traceparent,tracestate FROM image_jobs
|
||||||
|
WHERE state='queued' AND NOT published AND next_at<=clock_timestamp()
|
||||||
|
ORDER BY next_at,id LIMIT 1 FOR UPDATE SKIP LOCKED`).Scan(&j.JobID, &j.AttachmentID, &j.Version, &j.Attempt, &created, &parent, &state)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
j.CreatedAt = stamp(created)
|
||||||
|
payload, err := json.Marshal(j)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
ctx, span := a.telemetry.startJob(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state}, j, true)
|
||||||
|
defer func() { endSpan(span, result) }()
|
||||||
|
carrier := propagation.MapCarrier{}
|
||||||
|
traceContext.Inject(ctx, carrier)
|
||||||
|
values := map[string]any{"job": string(payload)}
|
||||||
|
for key, value := range carrier {
|
||||||
|
values[key] = value
|
||||||
|
}
|
||||||
|
injectImageFault("before_publish", j.AttachmentID)
|
||||||
|
// XADD replies after the broker's AOF durability boundary. A lost reply
|
||||||
|
// or crash before the SQL commit causes another delivery of the same job.
|
||||||
|
err = broker.XAdd(ctx, &redis.XAddArgs{Stream: imageStream, Values: values}).Err()
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
injectImageFault("after_publish", j.AttachmentID)
|
||||||
|
if _, err = tx.Exec(ctx, "UPDATE image_jobs SET published=true WHERE id=$1", j.JobID); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
err = tx.Commit(ctx)
|
||||||
|
if err == nil {
|
||||||
|
a.telemetry.event(ctx, "image.published", otellog.SeverityInfo,
|
||||||
|
attribute.String("job_id", j.JobID), attribute.Int("attempt", j.Attempt))
|
||||||
|
}
|
||||||
|
return true, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) dispatchImages(ctx context.Context, broker *redis.Client, attempts, retention int) {
|
||||||
|
cleanup := time.Now()
|
||||||
|
for ctx.Err() == nil {
|
||||||
|
step, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||||
|
recoverErr := a.recoverImage(step, attempts)
|
||||||
|
published, publishErr := a.publishImage(step, broker)
|
||||||
|
cancel()
|
||||||
|
if recoverErr != nil || publishErr != nil {
|
||||||
|
slog.Warn("image outbox unavailable", "recover_failed", recoverErr != nil, "publish_failed", publishErr != nil)
|
||||||
|
}
|
||||||
|
if time.Now().After(cleanup) {
|
||||||
|
step, cancel = context.WithTimeout(ctx, 5*time.Second)
|
||||||
|
if err := a.cleanStaging(step, retention); err != nil && ctx.Err() == nil {
|
||||||
|
slog.Warn("staging cleanup incomplete")
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
cleanup = time.Now().Add(15 * time.Second)
|
||||||
|
}
|
||||||
|
if !published || recoverErr != nil {
|
||||||
|
waitImage(ctx, 300*time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitImage(ctx context.Context, delay time.Duration) {
|
||||||
|
timer := time.NewTimer(delay)
|
||||||
|
defer timer.Stop()
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
case <-timer.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) consumeImages(ctx context.Context, broker *redis.Client, attempts int, timeout time.Duration) {
|
||||||
|
cursor := "0-0"
|
||||||
|
groupReady := false
|
||||||
|
for ctx.Err() == nil {
|
||||||
|
if !groupReady {
|
||||||
|
err := broker.XGroupCreateMkStream(ctx, imageStream, imageGroup, "0").Err()
|
||||||
|
if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
|
||||||
|
waitImage(ctx, time.Second)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
groupReady = true
|
||||||
|
}
|
||||||
|
messages, next, err := broker.XAutoClaim(ctx, &redis.XAutoClaimArgs{
|
||||||
|
Stream: imageStream, Group: imageGroup, Consumer: "worker", MinIdle: timeout + 10*time.Second, Start: cursor, Count: 1,
|
||||||
|
}).Result()
|
||||||
|
if err == nil {
|
||||||
|
cursor = next
|
||||||
|
if len(messages) == 0 {
|
||||||
|
var streams []redis.XStream
|
||||||
|
streams, err = broker.XReadGroup(ctx, &redis.XReadGroupArgs{
|
||||||
|
Group: imageGroup, Consumer: "worker", Streams: []string{imageStream, ">"}, Count: 1, Block: time.Second,
|
||||||
|
}).Result()
|
||||||
|
if err == nil && len(streams) > 0 {
|
||||||
|
messages = streams[0].Messages
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil && !errors.Is(err, redis.Nil) {
|
||||||
|
groupReady = false
|
||||||
|
waitImage(ctx, time.Second)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, message := range messages {
|
||||||
|
if err = a.handleImage(ctx, message, attempts, timeout); err != nil {
|
||||||
|
slog.Warn("image delivery left pending", "delivery_id", message.ID)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err = ackImage.Run(ctx, broker, []string{imageStream}, imageGroup, message.ID).Err(); err != nil {
|
||||||
|
slog.Warn("image acknowledgement unavailable", "delivery_id", message.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) handleImage(ctx context.Context, message redis.XMessage, attempts int, timeout time.Duration) (result error) {
|
||||||
|
var j imageJob
|
||||||
|
payload, ok := message.Values["job"].(string)
|
||||||
|
if !ok || len(payload) > 2048 || json.Unmarshal([]byte(payload), &j) != nil ||
|
||||||
|
j.SchemaVersion != 1 || j.Type != "attachment.process.v1" || j.Attempt < 1 || (j.Version != 1 && j.Version != 2) {
|
||||||
|
slog.Warn("invalid image delivery", "delivery_id", message.ID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, id := range []string{j.JobID, j.AttachmentID} {
|
||||||
|
if normalized, err := normalizeID(id); err != nil || normalized != id {
|
||||||
|
slog.Warn("invalid image delivery ID", "delivery_id", message.ID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parent, _ := message.Values["traceparent"].(string)
|
||||||
|
state, _ := message.Values["tracestate"].(string)
|
||||||
|
ctx, span := a.telemetry.startJob(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state}, j, false)
|
||||||
|
defer func() { endSpan(span, result) }()
|
||||||
|
claimCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||||
|
src, claimed, err := a.claimImage(claimCtx, j, timeout+5*time.Second)
|
||||||
|
cancel()
|
||||||
|
if err != nil || !claimed {
|
||||||
|
if err != nil {
|
||||||
|
a.telemetry.event(ctx, "image.claim_failed", otellog.SeverityError, attribute.String("job_id", j.JobID))
|
||||||
|
}
|
||||||
|
return err // Stale/duplicate attempts are no-ops. A processing row has a recoverable lease.
|
||||||
|
}
|
||||||
|
outcome := "error"
|
||||||
|
started := time.Now()
|
||||||
|
if a.telemetry != nil {
|
||||||
|
a.telemetry.workerBusy.Add(1)
|
||||||
|
defer a.telemetry.workerBusy.Add(-1)
|
||||||
|
}
|
||||||
|
defer func() { a.telemetry.finishJob(ctx, j, outcome, started) }()
|
||||||
|
injectImageFault("before_effect", j.AttachmentID)
|
||||||
|
processCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
var variants []Variant
|
||||||
|
switch {
|
||||||
|
case os.Getenv("LAB5_FAULT_ATTACHMENT") == j.AttachmentID && os.Getenv("LAB5_FAULT") == "invalid_image":
|
||||||
|
err = imageFailure("invalid_image")
|
||||||
|
case os.Getenv("LAB5_FAULT_ATTACHMENT") == j.AttachmentID &&
|
||||||
|
(os.Getenv("LAB5_FAULT") == "temporary" || (os.Getenv("LAB5_FAULT") == "temporary_once" && j.Attempt == 1)):
|
||||||
|
err = errors.New("test transient failure")
|
||||||
|
default:
|
||||||
|
variants, err = a.generateImage(processCtx, j, src)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
finishCtx, cancel := context.WithTimeout(ctx, 4*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err != nil {
|
||||||
|
code := "processing_failed"
|
||||||
|
var permanent imageFailure
|
||||||
|
if errors.As(err, &permanent) {
|
||||||
|
code = string(permanent)
|
||||||
|
}
|
||||||
|
next, saveErr := a.failImage(finishCtx, j, code, permanent != "", false, attempts)
|
||||||
|
if saveErr == nil {
|
||||||
|
outcome = next
|
||||||
|
}
|
||||||
|
span.SetAttributes(attribute.String("error.type", code))
|
||||||
|
return saveErr
|
||||||
|
}
|
||||||
|
seconds, committed, err := a.completeImage(finishCtx, j, variants)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !committed {
|
||||||
|
outcome = "lease_lost"
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
outcome = "ready"
|
||||||
|
if a.telemetry != nil && j.Version == 1 {
|
||||||
|
a.telemetry.readyTime.Record(ctx, seconds, metric.WithAttributes(attribute.String("job_type", j.Type)))
|
||||||
|
}
|
||||||
|
injectImageFault("after_commit", j.AttachmentID)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
global
|
||||||
|
log stdout format raw local0
|
||||||
|
maxconn 1024
|
||||||
|
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
|
||||||
|
|
||||||
|
defaults
|
||||||
|
log global
|
||||||
|
mode http
|
||||||
|
timeout connect 600ms
|
||||||
|
timeout client 40s
|
||||||
|
timeout server 40s
|
||||||
|
timeout http-request 3s
|
||||||
|
timeout http-keep-alive 5s
|
||||||
|
timeout check 700ms
|
||||||
|
retries 0
|
||||||
|
|
||||||
|
resolvers docker
|
||||||
|
nameserver dns 127.0.0.11:53
|
||||||
|
accepted_payload_size 8192
|
||||||
|
resolve_retries 2
|
||||||
|
timeout resolve 1s
|
||||||
|
timeout retry 1s
|
||||||
|
hold valid 1s
|
||||||
|
hold obsolete 1s
|
||||||
|
hold nx 1s
|
||||||
|
|
||||||
|
frontend public
|
||||||
|
bind :8443 ssl crt /run/ingress/tls.pem
|
||||||
|
log-format "status=%ST duration_ms=%Ta method=%HM backend=%b server=%s"
|
||||||
|
http-request del-header X-User-Id
|
||||||
|
http-request del-header X-Forwarded-For
|
||||||
|
http-request set-header X-Forwarded-Proto https
|
||||||
|
http-response set-header Strict-Transport-Security max-age=86400
|
||||||
|
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
|
||||||
|
server-template replica 1-4 api:8080 ssl sni str(api) verify required verifyhost api ca-file /run/client/ca.crt crt /run/client/tls.pem check check-sni api inter 500ms fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
ui = false
|
||||||
|
api_addr = "https://openbao:8200"
|
||||||
|
|
||||||
|
storage "pebbledb" {
|
||||||
|
path = "/openbao/file/store"
|
||||||
|
}
|
||||||
|
|
||||||
|
audit "file" "local" {
|
||||||
|
description = "HMAC-protected local audit log"
|
||||||
|
options = {
|
||||||
|
file_path = "/openbao/file/audit.json"
|
||||||
|
mode = "0600"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
listener "tcp" {
|
||||||
|
address = "0.0.0.0:8200"
|
||||||
|
tls_cert_file = "/run/lab-tls/tls.crt"
|
||||||
|
tls_key_file = "/run/lab-tls/tls.key"
|
||||||
|
tls_client_ca_file = "/run/lab-tls/ca.crt"
|
||||||
|
tls_min_version = "tls12"
|
||||||
|
tls_require_and_verify_client_cert = true
|
||||||
|
max_request_size = 65536
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
path "lab/data/{role}" {
|
||||||
|
capabilities = ["read"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
groups:
|
||||||
|
- name: messenger
|
||||||
|
rules:
|
||||||
|
- alert: APIFastBurn
|
||||||
|
expr: |
|
||||||
|
((sum(rate(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[30s])) / sum(rate(messenger_http_requests_total{route!="unmatched"}[30s]))) / 0.01 > 14.4)
|
||||||
|
and ((sum(rate(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[10s])) / sum(rate(messenger_http_requests_total{route!="unmatched"}[10s]))) / 0.01 > 14.4)
|
||||||
|
and (sum(increase(messenger_http_requests_total{route!="unmatched"}[30s])) >= 8)
|
||||||
|
and (sum(increase(messenger_http_requests_total{route!="unmatched"}[10s])) >= 3)
|
||||||
|
for: 2s
|
||||||
|
labels: {severity: page, slo: api}
|
||||||
|
annotations:
|
||||||
|
summary: "Доля 5xx на маршрутах API. Burn rate выше 14.4 в окнах 30s и 10s."
|
||||||
|
runbook: "RUNBOOK.md#api"
|
||||||
|
- alert: APISlowBurn
|
||||||
|
expr: |
|
||||||
|
((sum(rate(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[75s])) / sum(rate(messenger_http_requests_total{route!="unmatched"}[75s]))) / 0.01 > 6)
|
||||||
|
and ((sum(rate(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[25s])) / sum(rate(messenger_http_requests_total{route!="unmatched"}[25s]))) / 0.01 > 6)
|
||||||
|
and (sum(increase(messenger_http_requests_total{route!="unmatched"}[75s])) >= 15)
|
||||||
|
and (sum(increase(messenger_http_requests_total{route!="unmatched"}[25s])) >= 5)
|
||||||
|
for: 12s
|
||||||
|
labels: {severity: ticket, slo: api}
|
||||||
|
annotations:
|
||||||
|
summary: "Доля 5xx на маршрутах API. Burn rate выше 6 в окнах 75s и 25s."
|
||||||
|
runbook: "RUNBOOK.md#api"
|
||||||
|
- alert: ReadyFastBurn
|
||||||
|
expr: |
|
||||||
|
((sum(rate(messenger_attachment_slo_jobs_total{outcome="missed"}[30s])) / sum(rate(messenger_attachment_slo_jobs_total[30s]))) / 0.01 > 14.4)
|
||||||
|
and ((sum(rate(messenger_attachment_slo_jobs_total{outcome="missed"}[10s])) / sum(rate(messenger_attachment_slo_jobs_total[10s]))) / 0.01 > 14.4)
|
||||||
|
and (sum(increase(messenger_attachment_slo_jobs_total[30s])) >= 8)
|
||||||
|
and (sum(increase(messenger_attachment_slo_jobs_total[10s])) >= 3)
|
||||||
|
for: 2s
|
||||||
|
labels: {severity: page, slo: ready}
|
||||||
|
annotations:
|
||||||
|
summary: "Доля загрузок, не готовых за 5 секунд. Burn rate выше 14.4 в окнах 30s и 10s."
|
||||||
|
runbook: "RUNBOOK.md#ready"
|
||||||
|
- alert: ReadySlowBurn
|
||||||
|
expr: |
|
||||||
|
((sum(rate(messenger_attachment_slo_jobs_total{outcome="missed"}[75s])) / sum(rate(messenger_attachment_slo_jobs_total[75s]))) / 0.01 > 6)
|
||||||
|
and ((sum(rate(messenger_attachment_slo_jobs_total{outcome="missed"}[25s])) / sum(rate(messenger_attachment_slo_jobs_total[25s]))) / 0.01 > 6)
|
||||||
|
and (sum(increase(messenger_attachment_slo_jobs_total[75s])) >= 15)
|
||||||
|
and (sum(increase(messenger_attachment_slo_jobs_total[25s])) >= 5)
|
||||||
|
for: 12s
|
||||||
|
labels: {severity: ticket, slo: ready}
|
||||||
|
annotations:
|
||||||
|
summary: "Доля загрузок, не готовых за 5 секунд. Burn rate выше 6 в окнах 75s и 25s."
|
||||||
|
runbook: "RUNBOOK.md#ready"
|
||||||
|
- alert: QueueLagHigh
|
||||||
|
expr: messenger_queue_oldest_age_seconds > 5 and messenger_queue_depth > 0
|
||||||
|
for: 4s
|
||||||
|
labels: {severity: ticket}
|
||||||
|
annotations:
|
||||||
|
summary: "Старейшее ожидающее задание старше 5 секунд."
|
||||||
|
runbook: "RUNBOOK.md#ready"
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 127.0.0.1:14318
|
||||||
|
|
||||||
|
processors:
|
||||||
|
memory_limiter:
|
||||||
|
check_interval: 1s
|
||||||
|
limit_mib: 125
|
||||||
|
spike_limit_mib: 25
|
||||||
|
batch:
|
||||||
|
timeout: 1s
|
||||||
|
send_batch_size: 128
|
||||||
|
send_batch_max_size: 256
|
||||||
|
|
||||||
|
exporters:
|
||||||
|
otlphttp/prometheus:
|
||||||
|
metrics_endpoint: https://prometheus:9090/api/v1/otlp/v1/metrics
|
||||||
|
tls: &backend_tls
|
||||||
|
ca_file: /run/lab-tls/ca.crt
|
||||||
|
cert_file: /run/lab-tls/tls.crt
|
||||||
|
key_file: /run/lab-tls/tls.key
|
||||||
|
timeout: 2s
|
||||||
|
sending_queue: &bounded_queue
|
||||||
|
enabled: true
|
||||||
|
num_consumers: 1
|
||||||
|
queue_size: 16
|
||||||
|
retry_on_failure: &bounded_retry
|
||||||
|
enabled: true
|
||||||
|
initial_interval: 1s
|
||||||
|
max_interval: 2s
|
||||||
|
max_elapsed_time: 8s
|
||||||
|
otlphttp/loki:
|
||||||
|
endpoint: https://loki:3100/otlp
|
||||||
|
tls: *backend_tls
|
||||||
|
timeout: 2s
|
||||||
|
sending_queue: *bounded_queue
|
||||||
|
retry_on_failure: *bounded_retry
|
||||||
|
otlphttp/tempo:
|
||||||
|
endpoint: https://tempo:3200
|
||||||
|
tls: *backend_tls
|
||||||
|
timeout: 2s
|
||||||
|
sending_queue: *bounded_queue
|
||||||
|
retry_on_failure: *bounded_retry
|
||||||
|
|
||||||
|
service:
|
||||||
|
telemetry:
|
||||||
|
metrics:
|
||||||
|
readers:
|
||||||
|
- pull:
|
||||||
|
exporter:
|
||||||
|
prometheus:
|
||||||
|
host: 127.0.0.1
|
||||||
|
port: 8888
|
||||||
|
pipelines:
|
||||||
|
metrics:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlphttp/prometheus]
|
||||||
|
logs:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlphttp/loki]
|
||||||
|
traces:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlphttp/tempo]
|
||||||
@@ -0,0 +1,810 @@
|
|||||||
|
{
|
||||||
|
"uid": "messenger-lab6",
|
||||||
|
"title": "Lab 6 · Messenger",
|
||||||
|
"description": "OpenTelemetry API и очереди изображений",
|
||||||
|
"tags": [
|
||||||
|
"messenger",
|
||||||
|
"opentelemetry"
|
||||||
|
],
|
||||||
|
"schemaVersion": 39,
|
||||||
|
"refresh": "5s",
|
||||||
|
"time": {
|
||||||
|
"from": "now-15m",
|
||||||
|
"to": "now"
|
||||||
|
},
|
||||||
|
"timezone": "browser",
|
||||||
|
"panels": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "Запросы API",
|
||||||
|
"description": "Интенсивность по двум API-репликам. Readiness и liveness выключены на этапе инструментации.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 0,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "reqps"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[30s]))",
|
||||||
|
"legendFormat": "известные маршруты",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[30s]))",
|
||||||
|
"legendFormat": "5xx",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "Ошибки API",
|
||||||
|
"description": "5xx из приложения на известных маршрутах. 4xx входят в знаменатель.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 0,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "(sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[30s])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[30s])))",
|
||||||
|
"legendFormat": "5xx / все",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "vector(0.01)",
|
||||||
|
"legendFormat": "допустимая доля",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "Задержка API",
|
||||||
|
"description": "Перцентили из общих bucket всех реплик. Первая минута и низкий трафик дают шумную оценку.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 8,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_http_duration_seconds_bucket[1m])))",
|
||||||
|
"legendFormat": "p50",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket[1m])))",
|
||||||
|
"legendFormat": "p95",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket[1m])))",
|
||||||
|
"legendFormat": "p99",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Попытки worker",
|
||||||
|
"description": "Считаются обработанные попытки по исходу. Повторная попытка учитывается отдельно.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 8,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "ops"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum by (outcome) (rate(messenger_job_attempts_total[30s]))",
|
||||||
|
"legendFormat": "{{outcome}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Задержка попытки worker",
|
||||||
|
"description": "От захвата lease до записи итога попытки или решения о повторе.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 16,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
|
||||||
|
"legendFormat": "p50",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
|
||||||
|
"legendFormat": "p95",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
|
||||||
|
"legendFormat": "p99",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"title": "Время до ready",
|
||||||
|
"description": "SQL-время от принятия загрузки до записи ready. Гистограмма включает завершившиеся первые публикации.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 16,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))",
|
||||||
|
"legendFormat": "p50",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))",
|
||||||
|
"legendFormat": "p95",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))",
|
||||||
|
"legendFormat": "p99",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 7,
|
||||||
|
"title": "Глубина очереди",
|
||||||
|
"description": "Строки outbox в queued, в том числе ожидающие XADD и backoff.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 24,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "messenger_queue_depth",
|
||||||
|
"legendFormat": "queued",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 8,
|
||||||
|
"title": "Возраст старейшего задания",
|
||||||
|
"description": "Возраст от создания самой старой строки outbox в queued.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 24,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "messenger_queue_oldest_age_seconds",
|
||||||
|
"legendFormat": "oldest",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "vector(5)",
|
||||||
|
"legendFormat": "порог",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 9,
|
||||||
|
"title": "Соединения PostgreSQL",
|
||||||
|
"description": "В процессе Acquire учитываются и короткие вызовы. Смотрите динамику при устойчивом ожидании.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 32,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "messenger_db_pool_used",
|
||||||
|
"legendFormat": "{{job}} {{instance}} / занято",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "messenger_db_pool_capacity",
|
||||||
|
"legendFormat": "{{job}} {{instance}} / лимит",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"expr": "messenger_db_pool_acquiring",
|
||||||
|
"legendFormat": "{{job}} {{instance}} / получение",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 10,
|
||||||
|
"title": "Получение соединения при пустом пуле",
|
||||||
|
"description": "Производная EmptyAcquireCount pgxpool. Включает ожидание создания соединения.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 32,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "ops"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "rate(messenger_db_pool_waits_total[30s])",
|
||||||
|
"legendFormat": "{{job}} {{instance}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 11,
|
||||||
|
"title": "Занятые слоты worker",
|
||||||
|
"description": "Только свежие показания. Снимки с шагом 2 с могут пропускать очень короткие задания.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 40,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum(messenger_worker_busy and (time() - timestamp(messenger_worker_busy) < 8)) / sum(messenger_worker_capacity and (time() - timestamp(messenger_worker_capacity) < 8))",
|
||||||
|
"legendFormat": "busy / capacity",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "avg_over_time((sum(messenger_worker_busy and (time() - timestamp(messenger_worker_busy) < 8)) / sum(messenger_worker_capacity and (time() - timestamp(messenger_worker_capacity) < 8)))[30s:2s])",
|
||||||
|
"legendFormat": "среднее за 30 с",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 12,
|
||||||
|
"title": "CPU контейнеров приложения",
|
||||||
|
"description": "CPU-seconds / wall-second по cgroup v2, включая дочерний Pillow в worker.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 40,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "cores"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "rate(messenger_container_cpu_seconds_total[30s])",
|
||||||
|
"legendFormat": "{{job}} {{instance}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 13,
|
||||||
|
"title": "RAM контейнеров приложения",
|
||||||
|
"description": "Текущий memory.current cgroup v2.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 48,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "bytes"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "messenger_container_memory_bytes",
|
||||||
|
"legendFormat": "{{job}} {{instance}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 14,
|
||||||
|
"title": "SLI за 30 минут",
|
||||||
|
"description": "Каждый upload попадает в когорту по истечении 5 с. Без трафика SLI отсутствует.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 48,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "1 - (sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[30m])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[30m])))",
|
||||||
|
"legendFormat": "API",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "1 - (sum(rate(messenger_attachment_slo_jobs_total{outcome=\"missed\"}[30m])) / sum(rate(messenger_attachment_slo_jobs_total[30m])))",
|
||||||
|
"legendFormat": "ready ≤ 5 с",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"expr": "vector(0.99)",
|
||||||
|
"legendFormat": "цель",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 15,
|
||||||
|
"title": "Burn rate",
|
||||||
|
"description": "Burn rate 1 соответствует расходу бюджета с нормативной скоростью.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 56,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "(sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[10s])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[10s]))) / 0.01",
|
||||||
|
"legendFormat": "API 10s",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "(sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[30s])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[30s]))) / 0.01",
|
||||||
|
"legendFormat": "API 30s",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"expr": "(sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[25s])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[25s]))) / 0.01",
|
||||||
|
"legendFormat": "API 25s",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "D",
|
||||||
|
"expr": "(sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[75s])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[75s]))) / 0.01",
|
||||||
|
"legendFormat": "API 75s",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "E",
|
||||||
|
"expr": "(sum(rate(messenger_attachment_slo_jobs_total{outcome=\"missed\"}[10s])) / sum(rate(messenger_attachment_slo_jobs_total[10s]))) / 0.01",
|
||||||
|
"legendFormat": "Ready 10s",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "F",
|
||||||
|
"expr": "(sum(rate(messenger_attachment_slo_jobs_total{outcome=\"missed\"}[30s])) / sum(rate(messenger_attachment_slo_jobs_total[30s]))) / 0.01",
|
||||||
|
"legendFormat": "Ready 30s",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "G",
|
||||||
|
"expr": "(sum(rate(messenger_attachment_slo_jobs_total{outcome=\"missed\"}[25s])) / sum(rate(messenger_attachment_slo_jobs_total[25s]))) / 0.01",
|
||||||
|
"legendFormat": "Ready 25s",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "H",
|
||||||
|
"expr": "(sum(rate(messenger_attachment_slo_jobs_total{outcome=\"missed\"}[75s])) / sum(rate(messenger_attachment_slo_jobs_total[75s]))) / 0.01",
|
||||||
|
"legendFormat": "Ready 75s",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 16,
|
||||||
|
"title": "Alerts в Prometheus",
|
||||||
|
"description": "Локальная история pending и firing за выбранный период.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 56,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "ALERTS{alertname=~\"APIFastBurn|APISlowBurn|ReadyFastBurn|ReadySlowBurn|QueueLagHigh\"}",
|
||||||
|
"legendFormat": "{{alertname}} / {{alertstate}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 17,
|
||||||
|
"title": "Потери Collector",
|
||||||
|
"description": "Число элементов в терминально неотправленных или не поставленных в очередь батчах за минуту.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 64,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum by (exporter) (increase({__name__=~\"otelcol_exporter_send_failed_(spans|log_records|metric_points)(_total)?\"}[1m]))",
|
||||||
|
"legendFormat": "{{exporter}} / send failed",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "sum by (exporter) (increase({__name__=~\"otelcol_exporter_enqueue_failed_(spans|log_records|metric_points)(_total)?\"}[1m]))",
|
||||||
|
"legendFormat": "{{exporter}} / enqueue failed",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "lab-prom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 18,
|
||||||
|
"title": "Логи API и worker",
|
||||||
|
"description": "В деталях записи есть trace_id и span_id. Ссылка Trace открывает Tempo.",
|
||||||
|
"type": "logs",
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "lab-loki"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 64,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "none"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "{service_name=~\"messenger-api|messenger-worker\"}",
|
||||||
|
"legendFormat": "",
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "lab-loki"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
providers:
|
||||||
|
- name: Lab 6
|
||||||
|
folder: Messenger
|
||||||
|
type: file
|
||||||
|
allowUiUpdates: false
|
||||||
|
options:
|
||||||
|
path: /var/lib/grafana/dashboards
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
datasources:
|
||||||
|
- name: Prometheus
|
||||||
|
uid: lab-prom
|
||||||
|
type: prometheus
|
||||||
|
url: https://prometheus:9090
|
||||||
|
access: proxy
|
||||||
|
isDefault: true
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
tlsAuth: true
|
||||||
|
tlsAuthWithCACert: true
|
||||||
|
timeInterval: 2s
|
||||||
|
prometheusType: Prometheus
|
||||||
|
prometheusVersion: 3.5.0
|
||||||
|
# TLS_MATERIAL
|
||||||
|
- name: Loki
|
||||||
|
uid: lab-loki
|
||||||
|
type: loki
|
||||||
|
url: https://loki:3100
|
||||||
|
access: proxy
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
tlsAuth: true
|
||||||
|
tlsAuthWithCACert: true
|
||||||
|
derivedFields:
|
||||||
|
- name: Trace
|
||||||
|
matcherType: label
|
||||||
|
matcherRegex: trace_id
|
||||||
|
datasourceUid: lab-tempo
|
||||||
|
url: '$${__value.raw}'
|
||||||
|
# TLS_MATERIAL
|
||||||
|
- name: Tempo
|
||||||
|
uid: lab-tempo
|
||||||
|
type: tempo
|
||||||
|
url: https://tempo:3200
|
||||||
|
access: proxy
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
tlsAuth: true
|
||||||
|
tlsAuthWithCACert: true
|
||||||
|
tracesToLogsV2:
|
||||||
|
datasourceUid: lab-loki
|
||||||
|
tags:
|
||||||
|
- {key: service.name, value: service_name}
|
||||||
|
spanStartTimeShift: "-30s"
|
||||||
|
spanEndTimeShift: "30s"
|
||||||
|
customQuery: true
|
||||||
|
query: '{service_name=~"messenger-api|messenger-dispatcher|messenger-worker"} | trace_id="$${__span.traceId}" | span_id="$${__span.spanId}"'
|
||||||
|
# TLS_MATERIAL
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
auth_enabled: false
|
||||||
|
server:
|
||||||
|
http_listen_address: 127.0.0.1
|
||||||
|
http_listen_port: 13100
|
||||||
|
grpc_listen_address: 127.0.0.1
|
||||||
|
common:
|
||||||
|
instance_addr: 127.0.0.1
|
||||||
|
path_prefix: /loki
|
||||||
|
storage:
|
||||||
|
filesystem:
|
||||||
|
chunks_directory: /loki/chunks
|
||||||
|
rules_directory: /loki/rules
|
||||||
|
replication_factor: 1
|
||||||
|
ring:
|
||||||
|
kvstore:
|
||||||
|
store: inmemory
|
||||||
|
schema_config:
|
||||||
|
configs:
|
||||||
|
- from: 2024-01-01
|
||||||
|
store: tsdb
|
||||||
|
object_store: filesystem
|
||||||
|
schema: v13
|
||||||
|
index:
|
||||||
|
prefix: index_
|
||||||
|
period: 24h
|
||||||
|
limits_config:
|
||||||
|
allow_structured_metadata: true
|
||||||
|
retention_period: 168h
|
||||||
|
otlp_config:
|
||||||
|
resource_attributes:
|
||||||
|
ignore_defaults: true
|
||||||
|
attributes_config:
|
||||||
|
- attributes: [service.name]
|
||||||
|
action: index_label
|
||||||
|
compactor:
|
||||||
|
working_directory: /loki/compactor
|
||||||
|
retention_enabled: true
|
||||||
|
delete_request_store: filesystem
|
||||||
|
analytics:
|
||||||
|
reporting_enabled: false
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
global:
|
||||||
|
scrape_interval: 2s
|
||||||
|
evaluation_interval: 2s
|
||||||
|
|
||||||
|
storage:
|
||||||
|
tsdb:
|
||||||
|
out_of_order_time_window: 30s
|
||||||
|
otlp:
|
||||||
|
promote_resource_attributes: [service.name, service.version, deployment.environment.name]
|
||||||
|
translation_strategy: UnderscoreEscapingWithSuffixes
|
||||||
|
|
||||||
|
rule_files: [/etc/prometheus/alerts.yml]
|
||||||
|
scrape_configs:
|
||||||
|
- job_name: otel-collector
|
||||||
|
scheme: https
|
||||||
|
tls_config:
|
||||||
|
ca_file: /run/lab-tls/ca.crt
|
||||||
|
cert_file: /run/lab-tls/tls.crt
|
||||||
|
key_file: /run/lab-tls/tls.key
|
||||||
|
static_configs:
|
||||||
|
- targets: [otel-collector:4318]
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
server:
|
||||||
|
http_listen_address: 127.0.0.1
|
||||||
|
http_listen_port: 13200
|
||||||
|
grpc_listen_address: 127.0.0.1
|
||||||
|
distributor:
|
||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 127.0.0.1:14318
|
||||||
|
ingester:
|
||||||
|
max_block_duration: 1m
|
||||||
|
compactor:
|
||||||
|
compaction:
|
||||||
|
block_retention: 168h
|
||||||
|
storage:
|
||||||
|
trace:
|
||||||
|
backend: local
|
||||||
|
wal:
|
||||||
|
path: /var/tempo/wal
|
||||||
|
local:
|
||||||
|
path: /var/tempo/blocks
|
||||||
|
usage_report:
|
||||||
|
reporting_enabled: false
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
DB_API="$(cat /run/db-secret/db_api)" DB_WORKER="$(cat /run/db-secret/db_worker)" \
|
||||||
|
DB_DISPATCHER="$(cat /run/db-secret/db_dispatcher)" DB_JOBS="$(cat /run/db-secret/db_jobs)" \
|
||||||
|
psql -X --quiet --set ON_ERROR_STOP=1 --username messenger --dbname messenger <<'SQL'
|
||||||
|
\getenv api DB_API
|
||||||
|
\getenv dispatcher DB_DISPATCHER
|
||||||
|
\getenv worker DB_WORKER
|
||||||
|
\getenv jobs DB_JOBS
|
||||||
|
CREATE ROLE lab_api LOGIN PASSWORD :'api';
|
||||||
|
CREATE ROLE lab_dispatcher LOGIN PASSWORD :'dispatcher';
|
||||||
|
CREATE ROLE lab_worker LOGIN PASSWORD :'worker';
|
||||||
|
CREATE ROLE lab_jobs LOGIN PASSWORD :'jobs';
|
||||||
|
SQL
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
install -o postgres -g postgres -m 0600 /run/lab-tls/tls.key /tmp/postgres.key
|
||||||
|
exec docker-entrypoint.sh "$@"
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
local all messenger trust
|
||||||
|
local all all reject
|
||||||
|
hostssl messenger all 0.0.0.0/0 scram-sha-256
|
||||||
|
hostssl messenger all ::/0 scram-sha-256
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"Version": "2012-10-17",
|
||||||
|
"Statement": [
|
||||||
|
{"Effect": "Allow", "Action": ["s3:GetBucketLocation"], "Resource": ["arn:aws:s3:::messenger-attachments"]},
|
||||||
|
{"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::messenger-attachments"], "Condition": {"StringLike": {"s3:prefix": ["staging/*"]}}},
|
||||||
|
{"Effect": "Allow", "Action": ["s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||||
|
cp /run/lab-ca/ca.crt "$MC_CONFIG_DIR/certs/CAs/lab.crt"
|
||||||
|
login() {
|
||||||
|
mc alias set --api S3v4 local https://s3:9000 \
|
||||||
|
"$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null 2>&1
|
||||||
|
}
|
||||||
|
attempt=0
|
||||||
|
until login && mc ready local >/dev/null 2>&1; do
|
||||||
|
attempt=$((attempt + 1))
|
||||||
|
if [ "$attempt" -ge 20 ]; then echo 'S3 TLS readiness failed' >&2; exit 1; fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
attach_policy() {
|
||||||
|
if ! mc admin policy attach local "$1" --user "$2" >/dev/null 2>&1; then
|
||||||
|
mc admin policy entities local "$1" --user "$2" 2>/dev/null | grep -Fq "$2"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
if [ "${1:-}" = rotate-worker ]; then
|
||||||
|
# The operator supplies the new key over stdin, never as a Compose argument.
|
||||||
|
IFS= read -r user
|
||||||
|
IFS= read -r password
|
||||||
|
mc admin user add local "$user" "$password" >/dev/null 2>&1 || { echo 'Worker S3 user update failed' >&2; exit 1; }
|
||||||
|
attach_policy messenger-worker "$user" || { echo 'Worker S3 policy verification failed' >&2; exit 1; }
|
||||||
|
echo 'Worker S3 key updated'
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
mc mb --ignore-existing local/messenger-attachments >/dev/null
|
||||||
|
mc anonymous set none local/messenger-attachments >/dev/null
|
||||||
|
for role in api dispatcher worker; do
|
||||||
|
case "$role" in api) policy=policy;; *) policy="$role-policy";; esac
|
||||||
|
case "$role" in api) file=s3-policy.json;; *) file="s3-$policy.json";; esac
|
||||||
|
user="$(cat "/run/s3-setup/${role}_user")"
|
||||||
|
# Existing users may have been rotated. Provisioning must not reset them.
|
||||||
|
if ! mc admin user info local "$user" >/dev/null 2>&1; then
|
||||||
|
mc admin user add local "$user" "$(cat "/run/s3-setup/${role}_key")" >/dev/null 2>&1
|
||||||
|
fi
|
||||||
|
mc admin policy create local "messenger-$role" "/bootstrap/$file" >/dev/null
|
||||||
|
attach_policy "messenger-$role" "$user"
|
||||||
|
done
|
||||||
|
echo 'Private bucket and restricted service accounts ready'
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"Version": "2012-10-17",
|
||||||
|
"Statement": [
|
||||||
|
{"Effect": "Allow", "Action": ["s3:GetBucketLocation", "s3:ListBucket"], "Resource": ["arn:aws:s3:::messenger-attachments"]},
|
||||||
|
{"Effect": "Allow", "Action": ["s3:PutObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]},
|
||||||
|
{"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/original/*", "arn:aws:s3:::messenger-attachments/thumbnail/*", "arn:aws:s3:::messenger-attachments/crop/*", "arn:aws:s3:::messenger-attachments/optimized/*"]}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"Version": "2012-10-17",
|
||||||
|
"Statement": [
|
||||||
|
{"Effect": "Allow", "Action": ["s3:GetBucketLocation"], "Resource": ["arn:aws:s3:::messenger-attachments"]},
|
||||||
|
{"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]},
|
||||||
|
{"Effect": "Allow", "Action": ["s3:PutObject", "s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/original/*", "arn:aws:s3:::messenger-attachments/thumbnail/*", "arn:aws:s3:::messenger-attachments/crop/*", "arn:aws:s3:::messenger-attachments/optimized/*"]}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
bind 127.0.0.1
|
||||||
|
port 16379
|
||||||
|
protected-mode yes
|
||||||
|
aclfile /run/lab-acl/broker
|
||||||
|
dir /data
|
||||||
|
appendonly yes
|
||||||
|
appendfsync always
|
||||||
|
maxmemory 128mb
|
||||||
|
maxmemory-policy noeviction
|
||||||
|
save ""
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
bind 0.0.0.0
|
||||||
|
port 0
|
||||||
|
tls-port 6379
|
||||||
|
tls-cert-file /run/lab-tls/tls.crt
|
||||||
|
tls-key-file /run/lab-tls/tls.key
|
||||||
|
tls-ca-cert-file /run/lab-tls/ca.crt
|
||||||
|
tls-auth-clients no
|
||||||
|
aclfile /run/lab-acl/sessions
|
||||||
|
dir /data
|
||||||
|
appendonly yes
|
||||||
|
appendfsync always
|
||||||
|
maxmemory 128mb
|
||||||
|
maxmemory-policy noeviction
|
||||||
|
save ""
|
||||||
@@ -0,0 +1,496 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"github.com/minio/minio-go/v7"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
|
)
|
||||||
|
|
||||||
|
type App struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
sessions *redis.Client
|
||||||
|
secret []byte
|
||||||
|
ttl time.Duration
|
||||||
|
slots, kdf chan struct{}
|
||||||
|
stopping atomic.Bool
|
||||||
|
dummyHash string
|
||||||
|
instance string
|
||||||
|
idempotencyTTL time.Duration
|
||||||
|
s3 *minio.Client
|
||||||
|
bucket string
|
||||||
|
uploadSlots, decodeSlot chan struct{}
|
||||||
|
telemetry *telemetry
|
||||||
|
}
|
||||||
|
|
||||||
|
func env(key, value string) string {
|
||||||
|
if v := os.Getenv(key); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
func positive(key string, fallback int) int {
|
||||||
|
n, e := strconv.Atoi(env(key, strconv.Itoa(fallback)))
|
||||||
|
if e != nil || n <= 0 {
|
||||||
|
panic("invalid positive configuration: " + key)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
func secretFile(key string) (string, error) {
|
||||||
|
b, e := os.ReadFile(os.Getenv(key))
|
||||||
|
if e != nil {
|
||||||
|
return "", fmt.Errorf("cannot read %s", key)
|
||||||
|
}
|
||||||
|
s := strings.TrimSpace(string(b))
|
||||||
|
if s == "" {
|
||||||
|
return "", fmt.Errorf("empty %s", key)
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) dispatch(ctx context.Context, w http.ResponseWriter, r *http.Request) (int, any, error) {
|
||||||
|
path := r.URL.Path
|
||||||
|
if r.Method == "GET" && (path == "/health/live" || path == "/health/ready") {
|
||||||
|
if path == "/health/ready" && (a.stopping.Load() || a.db.Ping(ctx) != nil || a.sessions.Ping(ctx).Err() != nil || !a.s3Ready(ctx)) {
|
||||||
|
return 0, nil, unavailable()
|
||||||
|
}
|
||||||
|
return 200, map[string]string{"status": "ok"}, nil
|
||||||
|
}
|
||||||
|
if a.stopping.Load() {
|
||||||
|
return 0, nil, unavailable()
|
||||||
|
}
|
||||||
|
if r.Method == "POST" && path == "/api/v1/auth/sessions" {
|
||||||
|
return a.login(ctx, r)
|
||||||
|
}
|
||||||
|
if r.Method == "POST" && path == "/api/v1/users" {
|
||||||
|
if err := a.rateLimit(ctx, "register", 24, 5); err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
body, err := readObject(w, r, 128*1024, []string{"username", "display_name", "password"})
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
name, err := textField(body, "username", 32)
|
||||||
|
if err != nil || !usernamePattern.MatchString(name) {
|
||||||
|
return 0, nil, invalid()
|
||||||
|
}
|
||||||
|
display, err := textField(body, "display_name", 100)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
p, err := password(body)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
if err = a.kdfSlot(ctx); err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
hash := hashPassword(p)
|
||||||
|
<-a.kdf
|
||||||
|
u, err := scanUser(a.db.QueryRow(ctx, "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4) RETURNING id::text,username,display_name,created_at", uuid(), name, []byte(display), hash))
|
||||||
|
return 201, u, err
|
||||||
|
}
|
||||||
|
user, key, err := a.authenticate(ctx, r)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
if r.Method == "DELETE" && path == "/api/v1/auth/sessions/current" {
|
||||||
|
count, e := a.sessions.Del(ctx, key).Result()
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, unavailable()
|
||||||
|
}
|
||||||
|
if count == 0 {
|
||||||
|
return 0, nil, unauthorized()
|
||||||
|
}
|
||||||
|
return 204, nil, nil
|
||||||
|
}
|
||||||
|
if r.Method == "GET" && path == "/api/v1/users/me" {
|
||||||
|
u, e := a.user(ctx, user)
|
||||||
|
return 200, u, e
|
||||||
|
}
|
||||||
|
if path == "/api/v1/chats" {
|
||||||
|
if r.Method == "GET" {
|
||||||
|
scope := "chats:" + user
|
||||||
|
limit, c, e := a.pagination(r, scope)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
page, e := a.listChats(ctx, user, limit, c, scope)
|
||||||
|
return 200, page, e
|
||||||
|
}
|
||||||
|
if r.Method == "POST" {
|
||||||
|
body, e := readObject(w, r, 128*1024, []string{"title", "member_ids"})
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
title, e := textField(body, "title", 100)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
var ids []string
|
||||||
|
if json.Unmarshal(body["member_ids"], &ids) != nil || len(ids) < 1 || len(ids) > 100 {
|
||||||
|
return 0, nil, invalid()
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for i, id := range ids {
|
||||||
|
normalized, e := normalizeID(id)
|
||||||
|
if e != nil || seen[normalized] {
|
||||||
|
return 0, nil, invalid()
|
||||||
|
}
|
||||||
|
ids[i] = normalized
|
||||||
|
seen[normalized] = true
|
||||||
|
}
|
||||||
|
if !seen[user] {
|
||||||
|
return 0, nil, invalid()
|
||||||
|
}
|
||||||
|
chat, e := a.createChat(ctx, title, ids)
|
||||||
|
return 201, chat, e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(path, "/api/v1/attachments/") {
|
||||||
|
parts := strings.Split(strings.TrimPrefix(path, "/api/v1/attachments/"), "/")
|
||||||
|
id, e := normalizeID(parts[0])
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
if r.Method != "GET" || len(parts) > 2 || (len(parts) == 2 && parts[1] != "content") {
|
||||||
|
return 0, nil, missing()
|
||||||
|
}
|
||||||
|
x, e := a.attachment(ctx, id, user)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
if len(parts) == 1 {
|
||||||
|
return 200, x, nil
|
||||||
|
}
|
||||||
|
b, e := a.content(ctx, r, x)
|
||||||
|
return 200, b, e
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(path, "/api/v1/chats/") {
|
||||||
|
parts := strings.Split(strings.TrimPrefix(path, "/api/v1/chats/"), "/")
|
||||||
|
id, e := normalizeID(parts[0])
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
if len(parts) > 2 || (len(parts) == 2 && parts[1] != "messages" && parts[1] != "attachments") {
|
||||||
|
return 0, nil, missing()
|
||||||
|
}
|
||||||
|
chat, e := a.chat(ctx, id, user)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
if len(parts) == 1 && r.Method == "GET" {
|
||||||
|
return 200, chat, nil
|
||||||
|
}
|
||||||
|
if len(parts) == 2 && parts[1] == "attachments" {
|
||||||
|
if r.Method != "POST" {
|
||||||
|
return 0, nil, missing()
|
||||||
|
}
|
||||||
|
x, e := a.upload(ctx, w, r, id, user)
|
||||||
|
return 202, x, e
|
||||||
|
}
|
||||||
|
if len(parts) == 2 {
|
||||||
|
if r.Method == "GET" {
|
||||||
|
scope := "messages:" + id
|
||||||
|
limit, c, e := a.pagination(r, scope)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
page, e := a.history(ctx, id, limit, c, scope)
|
||||||
|
return 200, page, e
|
||||||
|
}
|
||||||
|
if r.Method == "POST" {
|
||||||
|
keys := r.Header.Values("Idempotency-Key")
|
||||||
|
if len(keys) != 1 || !idempotencyPattern.MatchString(keys[0]) {
|
||||||
|
return 0, nil, invalid()
|
||||||
|
}
|
||||||
|
body, e := readObject(w, r, 128*1024, []string{"text", "attachment_ids"})
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
text, ids, e := messageFields(body)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
m, e := a.createMessage(ctx, id, user, keys[0], text, ids)
|
||||||
|
return 201, m, e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0, nil, missing()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
start := time.Now()
|
||||||
|
requestID := uuid()
|
||||||
|
status := 500
|
||||||
|
ctx := r.Context()
|
||||||
|
health := r.Method == "GET" && (r.URL.Path == "/health/live" || r.URL.Path == "/health/ready")
|
||||||
|
method, route := safeHTTPRoute(r.Method, r.URL.Path)
|
||||||
|
if !health && a.telemetry != nil {
|
||||||
|
var span trace.Span
|
||||||
|
ctx, span = startSpan(ctx, method+" "+route, trace.WithSpanKind(trace.SpanKindServer),
|
||||||
|
trace.WithAttributes(attribute.String("http.request.method", method), attribute.String("http.route", route),
|
||||||
|
attribute.String("request.id", requestID)))
|
||||||
|
defer span.End()
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.Header().Set("X-Request-Id", requestID)
|
||||||
|
w.Header().Set("X-Instance-Id", a.instance)
|
||||||
|
fail := func(err error) {
|
||||||
|
var e apiError
|
||||||
|
var limited limitError
|
||||||
|
if errors.As(err, &limited) {
|
||||||
|
e = apiError{429, "rate_limited", "Try again later"}
|
||||||
|
w.Header().Set("Retry-After", strconv.Itoa(limited.seconds))
|
||||||
|
} else if !errors.As(err, &e) {
|
||||||
|
e = unavailable()
|
||||||
|
}
|
||||||
|
status = e.status
|
||||||
|
if status == 401 {
|
||||||
|
scheme := `Bearer realm="messenger"`
|
||||||
|
if r.URL.Path == "/api/v1/auth/sessions" {
|
||||||
|
scheme = `Basic realm="messenger", charset="UTF-8"`
|
||||||
|
}
|
||||||
|
w.Header().Set("WWW-Authenticate", scheme)
|
||||||
|
}
|
||||||
|
if status == 503 || (status == 429 && w.Header().Get("Retry-After") == "") {
|
||||||
|
w.Header().Set("Retry-After", "1")
|
||||||
|
}
|
||||||
|
w.WriteHeader(status)
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": e.code, "message": e.message, "request_id": requestID}})
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if recovered := recover(); recovered != nil {
|
||||||
|
if recovered == http.ErrAbortHandler {
|
||||||
|
panic(recovered)
|
||||||
|
}
|
||||||
|
fail(apiError{500, "internal_error", "Internal server error"})
|
||||||
|
}
|
||||||
|
if !health {
|
||||||
|
a.telemetry.finishHTTP(ctx, route, method, requestID, status, start)
|
||||||
|
if a.telemetry == nil && env("REQUEST_LOG", "1") == "1" {
|
||||||
|
slog.Info("request", "method", method, "route", route, "status", status,
|
||||||
|
"request_id", requestID, "duration_ms", time.Since(start).Milliseconds())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 || trustedPeer(r.TLS.PeerCertificates[0]) != nil {
|
||||||
|
fail(unavailable())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
work, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if !health {
|
||||||
|
select {
|
||||||
|
case a.slots <- struct{}{}:
|
||||||
|
defer func() { <-a.slots }()
|
||||||
|
default:
|
||||||
|
fail(unavailable())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
code, value, err := a.dispatch(work, w, r)
|
||||||
|
if err != nil {
|
||||||
|
fail(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
status = code
|
||||||
|
if b, ok := value.(binaryContent); ok {
|
||||||
|
writeContent(w, b)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(code)
|
||||||
|
if code != 204 {
|
||||||
|
json.NewEncoder(w).Encode(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func run() error {
|
||||||
|
if len(os.Args) > 1 {
|
||||||
|
switch os.Args[1] {
|
||||||
|
case "memory-snapshot":
|
||||||
|
return memorySnapshot()
|
||||||
|
case "gateway":
|
||||||
|
return gatewayCommand()
|
||||||
|
case "security-probe":
|
||||||
|
return securityProbe()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if env("SESSION_STORE", "valkey") != "valkey" {
|
||||||
|
return errors.New("SESSION_STORE must be valkey")
|
||||||
|
}
|
||||||
|
address := net.JoinHostPort(env("APP_HOST", "0.0.0.0"), env("APP_PORT", "8080"))
|
||||||
|
role := "api"
|
||||||
|
if len(os.Args) > 1 {
|
||||||
|
role = os.Args[1]
|
||||||
|
}
|
||||||
|
var secrets serviceSecrets
|
||||||
|
var err error
|
||||||
|
if role == "migrate" {
|
||||||
|
secrets.DatabaseURL, err = secretFile("DATABASE_URL_FILE")
|
||||||
|
} else {
|
||||||
|
var stop func()
|
||||||
|
secrets, stop, err = startSecrets(role)
|
||||||
|
if err == nil {
|
||||||
|
defer stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
cfg, err := databaseConfig(secrets.DatabaseURL, positive("DB_POOL_MAX", 8))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
dbTrace := &databaseTracer{}
|
||||||
|
cfg.ConnConfig.Tracer = dbTrace
|
||||||
|
startup, cancel := context.WithTimeout(context.Background(), 45*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
db, err := pgxpool.NewWithConfig(startup, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("database setup failed")
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
if len(os.Args) > 1 && os.Args[1] == "migrate" {
|
||||||
|
if err = migrate(startup, db); err != nil {
|
||||||
|
return errors.New("database migration failed")
|
||||||
|
}
|
||||||
|
slog.Info("migrations complete")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var schemaReady bool
|
||||||
|
if err = db.QueryRow(startup, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version='008_dispatch_recovery.sql')").Scan(&schemaReady); err != nil || !schemaReady {
|
||||||
|
return errors.New("run the migrate service before starting API")
|
||||||
|
}
|
||||||
|
if len(os.Args) > 1 {
|
||||||
|
return imageCommand(db, dbTrace, os.Args[1:], secrets)
|
||||||
|
}
|
||||||
|
signing := secrets.CursorKey
|
||||||
|
if len(signing) < 32 {
|
||||||
|
return errors.New("cursor secret too short")
|
||||||
|
}
|
||||||
|
options, err := redisTLS(secrets.CacheURL, false)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("invalid session store configuration")
|
||||||
|
}
|
||||||
|
options.PoolSize = 8
|
||||||
|
options.MaxActiveConns = 8
|
||||||
|
options.DialTimeout = time.Second
|
||||||
|
options.ReadTimeout = time.Second
|
||||||
|
options.WriteTimeout = time.Second
|
||||||
|
options.PoolTimeout = time.Second
|
||||||
|
options.MaxRetries = -1
|
||||||
|
options.ContextTimeoutEnabled = true
|
||||||
|
sessions := redis.NewClient(options)
|
||||||
|
defer sessions.Close()
|
||||||
|
hostname, err := os.Hostname()
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("cannot identify instance")
|
||||||
|
}
|
||||||
|
s3, bucket, err := s3Client(secrets)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a := &App{s3: s3, bucket: bucket, uploadSlots: make(chan struct{}, 5), decodeSlot: make(chan struct{}, 1), db: db, sessions: sessions, secret: []byte(signing), ttl: time.Duration(positive("SESSION_TTL_SECONDS", 3600)) * time.Second, slots: make(chan struct{}, positive("MAX_INFLIGHT", 32)), kdf: make(chan struct{}, 2), dummyHash: hashPassword("unknown-user-dummy-password"), instance: hostname, idempotencyTTL: time.Duration(positive("IDEMPOTENCY_TTL_SECONDS", 86400)) * time.Second}
|
||||||
|
if a.idempotencyTTL < 24*time.Hour {
|
||||||
|
return errors.New("idempotency retention must be at least 24 hours")
|
||||||
|
}
|
||||||
|
instruments, cancelTelemetry, err := startTelemetry("api", db, dbTrace)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer cancelTelemetry()
|
||||||
|
a.telemetry = instruments
|
||||||
|
tlsConfig, err := serverTLS([]string{"lb-client"})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
server := &http.Server{Addr: address, Handler: a, TLSConfig: tlsConfig, ReadHeaderTimeout: 2 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 35 * time.Second, IdleTimeout: 5 * time.Second, MaxHeaderBytes: 16 * 1024}
|
||||||
|
listener, err := net.Listen("tcp", address)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("listen failed")
|
||||||
|
}
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
if env("POOL_METRICS", "0") == "1" {
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
s := db.Stat()
|
||||||
|
slog.Info("pool", "instance", a.instance, "acquired", s.AcquiredConns(), "max", s.MaxConns(), "empty_acquires", s.EmptyAcquireCount(), "acquire_ns", s.AcquireDuration().Nanoseconds())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
<-ctx.Done()
|
||||||
|
a.stopping.Store(true)
|
||||||
|
slog.Info("shutdown started")
|
||||||
|
// Allow two LB readiness checks to drain this backend before closing it.
|
||||||
|
time.Sleep(1500 * time.Millisecond)
|
||||||
|
shutdown, cancel := context.WithTimeout(context.Background(), 6*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
err := server.Shutdown(shutdown)
|
||||||
|
if err != nil {
|
||||||
|
server.Close()
|
||||||
|
}
|
||||||
|
slog.Info("shutdown complete", "forced", err != nil)
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
slog.Info("listening", "address", address, "environment", env("APP_ENV", "lab"), "session_store", "valkey", "session_ttl_seconds", int(a.ttl.Seconds()))
|
||||||
|
if err = server.ServeTLS(listener, "", ""); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
|
return errors.New("serve failed")
|
||||||
|
}
|
||||||
|
<-done
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func databaseConfig(rawURL string, maxConns int) (*pgxpool.Config, error) {
|
||||||
|
parsed, err := url.Parse(rawURL)
|
||||||
|
if err != nil || parsed.Scheme != "postgres" || parsed.Host == "" ||
|
||||||
|
parsed.Query().Get("sslmode") != "verify-full" || parsed.Query().Get("sslrootcert") != tlsDir+"/ca.crt" {
|
||||||
|
return nil, errors.New("PostgreSQL requires verified TLS")
|
||||||
|
}
|
||||||
|
cfg, err := pgxpool.ParseConfig(rawURL)
|
||||||
|
if err != nil || cfg.ConnConfig.TLSConfig == nil || cfg.ConnConfig.TLSConfig.InsecureSkipVerify ||
|
||||||
|
len(cfg.ConnConfig.Fallbacks) != 0 || cfg.ConnConfig.TLSConfig.ServerName == "" {
|
||||||
|
return nil, errors.New("invalid database TLS configuration")
|
||||||
|
}
|
||||||
|
cfg.MaxConns = int32(maxConns)
|
||||||
|
cfg.ConnConfig.ConnectTimeout = 2 * time.Second
|
||||||
|
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "3000"
|
||||||
|
cfg.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
|
||||||
|
cfg.ConnConfig.RuntimeParams["synchronous_commit"] = "on"
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
func main() {
|
||||||
|
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))
|
||||||
|
if err := run(); err != nil {
|
||||||
|
slog.Error("startup failed", "reason", err.Error())
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Local operator command, never an HTTP endpoint. cgroup v2 records peaks
|
||||||
|
// between Docker samples too; the experiment recreates API cgroups per case.
|
||||||
|
func memorySnapshot() error {
|
||||||
|
result := map[string]uint64{}
|
||||||
|
for _, name := range []string{"memory.current", "memory.peak"} {
|
||||||
|
raw, err := os.ReadFile("/sys/fs/cgroup/" + name)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cgroup v2 %s unavailable", name)
|
||||||
|
}
|
||||||
|
value, err := strconv.ParseUint(strings.TrimSpace(string(raw)), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid cgroup %s", name)
|
||||||
|
}
|
||||||
|
result[name] = value
|
||||||
|
}
|
||||||
|
return json.NewEncoder(os.Stdout).Encode(result)
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
CREATE TABLE users (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||||
|
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||||
|
password_hash text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
CREATE TABLE chats (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
CREATE TABLE chat_members (
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id),
|
||||||
|
PRIMARY KEY (chat_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX chat_members_user_idx ON chat_members(user_id, chat_id);
|
||||||
|
CREATE INDEX chats_page_idx ON chats(created_at, id);
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||||
|
sender_id uuid NOT NULL,
|
||||||
|
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX messages_history_idx ON messages(chat_id, created_at, id);
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- PostgreSQL text cannot contain U+0000, although it is a valid JSON string
|
||||||
|
-- code point. Keep exact UTF-8 bytes for free-form API strings. The API checks
|
||||||
|
-- Unicode length/whitespace; these checks also bound stored byte lengths.
|
||||||
|
ALTER TABLE users DROP CONSTRAINT users_display_name_check;
|
||||||
|
ALTER TABLE users ALTER COLUMN display_name TYPE bytea USING convert_to(display_name,'UTF8');
|
||||||
|
ALTER TABLE users ADD CHECK (octet_length(display_name) BETWEEN 1 AND 400);
|
||||||
|
ALTER TABLE chats DROP CONSTRAINT chats_title_check;
|
||||||
|
ALTER TABLE chats ALTER COLUMN title TYPE bytea USING convert_to(title,'UTF8');
|
||||||
|
ALTER TABLE chats ADD CHECK (octet_length(title) BETWEEN 1 AND 400);
|
||||||
|
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
|
||||||
|
ALTER TABLE messages ALTER COLUMN text TYPE bytea USING convert_to(text,'UTF8');
|
||||||
|
ALTER TABLE messages ADD CHECK (octet_length(text) BETWEEN 1 AND 16000);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
CREATE TABLE message_keys (
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id),
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||||
|
key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||||
|
message_id uuid NOT NULL REFERENCES messages(id),
|
||||||
|
expires_at timestamptz NOT NULL,
|
||||||
|
PRIMARY KEY (user_id, chat_id, key)
|
||||||
|
);
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
CREATE TABLE attachments (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||||
|
owner_id uuid NOT NULL,
|
||||||
|
object_key text NOT NULL UNIQUE CHECK (object_key = 'original/' || id::text),
|
||||||
|
filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||||
|
content_type text NOT NULL CHECK (content_type IN ('image/png','image/jpeg')),
|
||||||
|
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||||
|
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||||
|
missing_since timestamptz,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
UNIQUE (chat_id,id),
|
||||||
|
FOREIGN KEY (chat_id,owner_id) REFERENCES chat_members(chat_id,user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX attachments_page_idx ON attachments(id);
|
||||||
|
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
|
||||||
|
ALTER TABLE messages ADD CHECK (octet_length(text) BETWEEN 0 AND 16000);
|
||||||
|
ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}';
|
||||||
|
ALTER TABLE messages ADD CHECK (cardinality(attachment_ids) <= 10);
|
||||||
|
CREATE TABLE message_attachments (
|
||||||
|
message_id uuid NOT NULL REFERENCES messages(id),
|
||||||
|
chat_id uuid NOT NULL,
|
||||||
|
attachment_id uuid NOT NULL,
|
||||||
|
PRIMARY KEY (message_id,attachment_id),
|
||||||
|
FOREIGN KEY (chat_id,attachment_id) REFERENCES attachments(chat_id,id)
|
||||||
|
);
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
ALTER TABLE attachments
|
||||||
|
ADD COLUMN status text NOT NULL DEFAULT 'ready' CHECK (status IN ('queued','processing','ready','failed')),
|
||||||
|
ADD COLUMN error_code text,
|
||||||
|
ADD COLUMN active_version integer NOT NULL DEFAULT 0,
|
||||||
|
ADD COLUMN result_version integer NOT NULL DEFAULT 0,
|
||||||
|
ADD COLUMN variants jsonb NOT NULL DEFAULT '[]',
|
||||||
|
ADD CHECK ((status='failed') = (error_code IS NOT NULL)),
|
||||||
|
ADD CHECK (active_version >= result_version AND result_version >= 0);
|
||||||
|
|
||||||
|
-- A queued row is also the transactional outbox entry. Keep completed rows as
|
||||||
|
-- the deduplication ledger and failed rows as the operator's dead-letter registry.
|
||||||
|
CREATE TABLE image_jobs (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||||
|
version integer NOT NULL CHECK (version IN (1,2)),
|
||||||
|
attempt integer NOT NULL DEFAULT 1,
|
||||||
|
cycle_start integer NOT NULL DEFAULT 1 CHECK (cycle_start BETWEEN 1 AND attempt),
|
||||||
|
state text NOT NULL DEFAULT 'queued' CHECK (state IN ('queued','processing','ready','failed')),
|
||||||
|
published boolean NOT NULL DEFAULT false,
|
||||||
|
next_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
lease_until timestamptz,
|
||||||
|
error_code text,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
UNIQUE (attachment_id,version),
|
||||||
|
CHECK ((state='processing') = (lease_until IS NOT NULL))
|
||||||
|
);
|
||||||
|
CREATE INDEX image_jobs_outbox ON image_jobs(next_at,id) WHERE state='queued' AND NOT published;
|
||||||
|
CREATE INDEX image_jobs_lease ON image_jobs(lease_until,id) WHERE state='processing';
|
||||||
|
|
||||||
|
CREATE TABLE image_job_replays (
|
||||||
|
job_id uuid NOT NULL REFERENCES image_jobs(id),
|
||||||
|
attempt integer NOT NULL,
|
||||||
|
previous_error text NOT NULL,
|
||||||
|
replayed_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
PRIMARY KEY (job_id,attempt)
|
||||||
|
);
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
ALTER TABLE image_jobs
|
||||||
|
ADD COLUMN traceparent text NOT NULL DEFAULT '',
|
||||||
|
ADD COLUMN tracestate text NOT NULL DEFAULT '',
|
||||||
|
ADD COLUMN ready_at timestamptz;
|
||||||
|
|
||||||
|
-- Use the historical ready timestamp for lab5 rows that already completed.
|
||||||
|
UPDATE image_jobs SET ready_at=updated_at WHERE state='ready';
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
|
||||||
|
REVOKE CONNECT, TEMPORARY ON DATABASE messenger FROM PUBLIC;
|
||||||
|
GRANT CONNECT ON DATABASE messenger TO lab_api,lab_dispatcher,lab_worker,lab_jobs;
|
||||||
|
GRANT USAGE ON SCHEMA public TO lab_api,lab_dispatcher,lab_worker,lab_jobs;
|
||||||
|
GRANT SELECT(version) ON schema_migrations TO lab_api,lab_dispatcher,lab_worker,lab_jobs;
|
||||||
|
|
||||||
|
GRANT SELECT, INSERT ON users,chats,chat_members,messages,attachments,message_attachments TO lab_api;
|
||||||
|
GRANT UPDATE(password_hash) ON users TO lab_api;
|
||||||
|
GRANT SELECT, INSERT, DELETE ON message_keys TO lab_api;
|
||||||
|
GRANT INSERT(id,attachment_id,version,traceparent,tracestate) ON image_jobs TO lab_api;
|
||||||
|
GRANT SELECT(attachment_id,version) ON image_jobs TO lab_api;
|
||||||
|
|
||||||
|
GRANT SELECT ON image_jobs TO lab_dispatcher,lab_worker,lab_jobs;
|
||||||
|
GRANT SELECT(id,result_version,status,updated_at) ON attachments TO lab_dispatcher;
|
||||||
|
GRANT UPDATE(published) ON image_jobs TO lab_dispatcher;
|
||||||
|
GRANT SELECT(id,active_version,result_version,content_type,size_bytes,sha256) ON attachments TO lab_worker;
|
||||||
|
GRANT UPDATE(status,updated_at,error_code,result_version,variants) ON attachments TO lab_worker;
|
||||||
|
GRANT UPDATE(state,lease_until,updated_at,error_code,ready_at,attempt,published,next_at) ON image_jobs TO lab_worker;
|
||||||
|
|
||||||
|
GRANT SELECT(id,active_version,result_version,status,updated_at) ON attachments TO lab_jobs;
|
||||||
|
GRANT UPDATE(active_version,status,error_code,updated_at) ON attachments TO lab_jobs;
|
||||||
|
GRANT INSERT(id,attachment_id,version,traceparent,tracestate) ON image_jobs TO lab_jobs;
|
||||||
|
GRANT UPDATE(state,attempt,cycle_start,error_code,published,next_at,updated_at) ON image_jobs TO lab_jobs;
|
||||||
|
GRANT INSERT ON image_job_replays TO lab_jobs;
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
-- An expired worker lease is recovered by the dispatcher before publishing.
|
||||||
|
GRANT SELECT(active_version) ON attachments TO lab_dispatcher;
|
||||||
|
GRANT UPDATE(status,error_code,updated_at) ON attachments TO lab_dispatcher;
|
||||||
|
GRANT UPDATE(state,lease_until,error_code,attempt,next_at,updated_at) ON image_jobs TO lab_dispatcher;
|
||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
"""Decode a bounded local input and write metadata-free variants for one job."""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import warnings
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||||
|
|
||||||
|
|
||||||
|
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||||
|
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||||
|
|
||||||
|
|
||||||
|
def fit(image, edge):
|
||||||
|
width, height = image.size
|
||||||
|
longest = max(width, height)
|
||||||
|
if longest <= edge:
|
||||||
|
return image
|
||||||
|
size = (max(1, width * edge // longest), max(1, height * edge // longest))
|
||||||
|
return image.resize(size, Image.Resampling.LANCZOS)
|
||||||
|
|
||||||
|
|
||||||
|
def white_rgb(image):
|
||||||
|
if image.mode == "RGBA":
|
||||||
|
background = Image.new("RGB", image.size, "white")
|
||||||
|
background.paste(image, mask=image.getchannel("A"))
|
||||||
|
return background
|
||||||
|
return image.convert("RGB")
|
||||||
|
|
||||||
|
|
||||||
|
def render(directory, mime, version):
|
||||||
|
try:
|
||||||
|
with Image.open(directory / "input", formats=("JPEG", "PNG")) as source:
|
||||||
|
if Image.MIME[source.format] != mime or source.width * source.height > Image.MAX_IMAGE_PIXELS:
|
||||||
|
return 2
|
||||||
|
source.seek(0)
|
||||||
|
# PNG may carry transparency in a tRNS chunk or in its alpha channel.
|
||||||
|
mode = "RGBA" if "A" in source.getbands() or "transparency" in source.info else "RGB"
|
||||||
|
ImageOps.exif_transpose(source, in_place=True)
|
||||||
|
image = source.convert(mode)
|
||||||
|
except (UnidentifiedImageError, OSError, ValueError, SyntaxError,
|
||||||
|
Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||||
|
return 2
|
||||||
|
|
||||||
|
square = min(image.size)
|
||||||
|
left = (image.width - square) // 2
|
||||||
|
top = (image.height - square) // 2
|
||||||
|
outputs = [
|
||||||
|
("thumbnail", fit(image, 256), "JPEG", 85),
|
||||||
|
("crop", image.resize((128, 128), Image.Resampling.LANCZOS,
|
||||||
|
box=(left, top, left + square, top + square)), "JPEG", 85),
|
||||||
|
("optimized", fit(image, 1280), "WEBP", 80 if version == "1" else 90),
|
||||||
|
]
|
||||||
|
variants = []
|
||||||
|
for name, pixels, format_name, quality in outputs:
|
||||||
|
clean = white_rgb(pixels)
|
||||||
|
clean.info.clear()
|
||||||
|
clean.save(directory / name, format=format_name, quality=quality)
|
||||||
|
variants.append({"width": clean.width, "height": clean.height})
|
||||||
|
print(json.dumps(variants))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(render(Path(sys.argv[1]), sys.argv[2], sys.argv[3]))
|
||||||
+239
@@ -0,0 +1,239 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
}
|
||||||
|
type Chat struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
MemberIDs []string `json:"member_ids"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
}
|
||||||
|
type Message struct {
|
||||||
|
AttachmentIDs []string `json:"attachment_ids"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
ChatID string `json:"chat_id"`
|
||||||
|
SenderID string `json:"sender_id"`
|
||||||
|
Text string `json:"text"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
}
|
||||||
|
type Page[T any] struct {
|
||||||
|
Items []T `json:"items"`
|
||||||
|
NextCursor *string `json:"next_cursor"`
|
||||||
|
}
|
||||||
|
type apiError struct {
|
||||||
|
status int
|
||||||
|
code, message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e apiError) Error() string { return e.code }
|
||||||
|
func invalid() apiError { return apiError{400, "invalid_request", "Invalid request"} }
|
||||||
|
func unavailable() apiError { return apiError{503, "unavailable", "Dependency unavailable"} }
|
||||||
|
func missing() apiError { return apiError{404, "not_found", "Object not found"} }
|
||||||
|
func unauthorized() apiError { return apiError{401, "unauthorized", "Valid Bearer session required"} }
|
||||||
|
|
||||||
|
func uuid() string {
|
||||||
|
b := make([]byte, 16)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
b[6] = (b[6] & 15) | 64
|
||||||
|
b[8] = (b[8] & 63) | 128
|
||||||
|
s := hex.EncodeToString(b)
|
||||||
|
return s[:8] + "-" + s[8:12] + "-" + s[12:16] + "-" + s[16:20] + "-" + s[20:]
|
||||||
|
}
|
||||||
|
|
||||||
|
var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
|
||||||
|
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||||
|
var idempotencyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||||
|
|
||||||
|
func normalizeID(s string) (string, error) {
|
||||||
|
if !uuidPattern.MatchString(s) {
|
||||||
|
return "", invalid()
|
||||||
|
}
|
||||||
|
return strings.ToLower(s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func textField(m map[string]json.RawMessage, key string, max int) (string, error) {
|
||||||
|
var s string
|
||||||
|
b, ok := m[key]
|
||||||
|
if !ok || string(b) == "null" || json.Unmarshal(b, &s) != nil || strings.TrimSpace(s) == "" || utf8.RuneCountInString(s) > max {
|
||||||
|
return "", invalid()
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reject duplicate keys, invalid UTF-8, and unpaired UTF-16 escapes rather than
|
||||||
|
// letting encoding/json silently replace malformed Unicode with U+FFFD.
|
||||||
|
func validUnicode(b []byte) bool {
|
||||||
|
if !utf8.Valid(b) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i := 0; i < len(b); i++ {
|
||||||
|
if b[i] != '\\' {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
if i >= len(b) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if b[i] != 'u' {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if i+4 >= len(b) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
n, e := strconv.ParseUint(string(b[i+1:i+5]), 16, 16)
|
||||||
|
if e != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
i += 4
|
||||||
|
if n >= 0xDC00 && n <= 0xDFFF {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if n >= 0xD800 && n <= 0xDBFF {
|
||||||
|
if i+6 >= len(b) || string(b[i+1:i+3]) != `\u` {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
low, e := strconv.ParseUint(string(b[i+3:i+7]), 16, 16)
|
||||||
|
if e != nil || low < 0xDC00 || low > 0xDFFF {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
i += 6
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
func readObject(w http.ResponseWriter, r *http.Request, max int, fields []string) (map[string]json.RawMessage, error) {
|
||||||
|
media, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||||
|
if err != nil || media != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
|
||||||
|
return nil, apiError{415, "unsupported_media_type", "Expected application/json UTF-8"}
|
||||||
|
}
|
||||||
|
b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, int64(max)))
|
||||||
|
if err != nil {
|
||||||
|
var large *http.MaxBytesError
|
||||||
|
if errors.As(err, &large) {
|
||||||
|
return nil, apiError{413, "payload_too_large", "Request body exceeds byte limit"}
|
||||||
|
}
|
||||||
|
return nil, invalid()
|
||||||
|
}
|
||||||
|
if !validUnicode(b) {
|
||||||
|
return nil, invalid()
|
||||||
|
}
|
||||||
|
d := json.NewDecoder(strings.NewReader(string(b)))
|
||||||
|
token, err := d.Token()
|
||||||
|
if err != nil || token != json.Delim('{') {
|
||||||
|
return nil, invalid()
|
||||||
|
}
|
||||||
|
m := map[string]json.RawMessage{}
|
||||||
|
for d.More() {
|
||||||
|
t, err := d.Token()
|
||||||
|
if err != nil {
|
||||||
|
return nil, invalid()
|
||||||
|
}
|
||||||
|
key, ok := t.(string)
|
||||||
|
if !ok {
|
||||||
|
return nil, invalid()
|
||||||
|
}
|
||||||
|
allowed := false
|
||||||
|
for _, f := range fields {
|
||||||
|
if key == f {
|
||||||
|
allowed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !allowed || m[key] != nil {
|
||||||
|
return nil, invalid()
|
||||||
|
}
|
||||||
|
var value json.RawMessage
|
||||||
|
if d.Decode(&value) != nil {
|
||||||
|
return nil, invalid()
|
||||||
|
}
|
||||||
|
m[key] = value
|
||||||
|
}
|
||||||
|
if _, err = d.Token(); err != nil {
|
||||||
|
return nil, invalid()
|
||||||
|
}
|
||||||
|
if _, err = d.Token(); err != io.EOF {
|
||||||
|
return nil, invalid()
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type cursor struct {
|
||||||
|
Scope string `json:"s"`
|
||||||
|
Time string `json:"t"`
|
||||||
|
ID string `json:"i"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) encodeCursor(scope, t, id string) string {
|
||||||
|
b, _ := json.Marshal(cursor{scope, t, id})
|
||||||
|
h := hmac.New(sha256.New, a.secret)
|
||||||
|
h.Write(b)
|
||||||
|
return base64.RawURLEncoding.EncodeToString(b) + "." + base64.RawURLEncoding.EncodeToString(h.Sum(nil))
|
||||||
|
}
|
||||||
|
func (a *App) pagination(r *http.Request, scope string) (int, cursor, error) {
|
||||||
|
values, e := url.ParseQuery(r.URL.RawQuery)
|
||||||
|
if e != nil {
|
||||||
|
return 0, cursor{}, invalid()
|
||||||
|
}
|
||||||
|
limit := 50
|
||||||
|
if v, ok := values["limit"]; ok {
|
||||||
|
if len(v) != 1 || v[0] == "" {
|
||||||
|
return 0, cursor{}, invalid()
|
||||||
|
}
|
||||||
|
for _, c := range v[0] {
|
||||||
|
if c < '0' || c > '9' {
|
||||||
|
return 0, cursor{}, invalid()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
limit, e = strconv.Atoi(v[0])
|
||||||
|
if e != nil || limit < 1 || limit > 100 {
|
||||||
|
return 0, cursor{}, invalid()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c := cursor{}
|
||||||
|
if v, ok := values["cursor"]; ok {
|
||||||
|
if len(v) != 1 || len(v[0]) > 1024 {
|
||||||
|
return 0, c, invalid()
|
||||||
|
}
|
||||||
|
parts := strings.Split(v[0], ".")
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return 0, c, invalid()
|
||||||
|
}
|
||||||
|
b, e := base64.RawURLEncoding.DecodeString(parts[0])
|
||||||
|
if e != nil {
|
||||||
|
return 0, c, invalid()
|
||||||
|
}
|
||||||
|
sig, e := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if e != nil {
|
||||||
|
return 0, c, invalid()
|
||||||
|
}
|
||||||
|
h := hmac.New(sha256.New, a.secret)
|
||||||
|
h.Write(b)
|
||||||
|
if !hmac.Equal(sig, h.Sum(nil)) || json.Unmarshal(b, &c) != nil || c.Scope != scope {
|
||||||
|
return 0, c, invalid()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return limit, c, nil
|
||||||
|
}
|
||||||
+252
@@ -0,0 +1,252 @@
|
|||||||
|
"""Operator-only OpenBao bootstrap and worker credential rotation."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
from bootstrap import CA, OPERATOR, PRIVATE, ROOT, client, db_url, openssl, redis_url, write
|
||||||
|
|
||||||
|
INIT = OPERATOR / "openbao-init.json"
|
||||||
|
ROTATION = OPERATOR / "worker-rotation"
|
||||||
|
ROLE_NAMES = ("api", "dispatcher", "worker", "jobs")
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, *args, **kwargs):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def bao_context(folder):
|
||||||
|
context = ssl.create_default_context(cafile=str(CA))
|
||||||
|
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||||
|
context.load_cert_chain(folder / "tls.crt", folder / "tls.key")
|
||||||
|
return context
|
||||||
|
|
||||||
|
|
||||||
|
def bao_url():
|
||||||
|
env = ROOT / ".env"
|
||||||
|
settings = dict(line.split("=", 1) for line in env.read_text(encoding="utf-8").splitlines()
|
||||||
|
if line and not line.lstrip().startswith("#") and "=" in line)
|
||||||
|
value = os.getenv("BAO_PORT", settings.get("BAO_PORT", "8200"))
|
||||||
|
return f"https://127.0.0.1:{int(value)}"
|
||||||
|
|
||||||
|
|
||||||
|
def request(path, *, method="GET", data=None, token=None, folder=None, timeout=5):
|
||||||
|
endpoint = bao_url() + "/v1/" + path
|
||||||
|
context = bao_context(folder or OPERATOR / "tls")
|
||||||
|
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect(),
|
||||||
|
urllib.request.HTTPSHandler(context=context))
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
if token:
|
||||||
|
headers["X-Vault-Token"] = token
|
||||||
|
body = None if data is None else json.dumps(data).encode()
|
||||||
|
req = urllib.request.Request(endpoint, body, headers, method=method)
|
||||||
|
try:
|
||||||
|
with opener.open(req, timeout=timeout) as response:
|
||||||
|
raw = response.read(256 * 1024)
|
||||||
|
return response.status, json.loads(raw) if raw else {}
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
error.close()
|
||||||
|
return error.code, {}
|
||||||
|
|
||||||
|
|
||||||
|
def required(path, **kwargs):
|
||||||
|
code, body = request(path, **kwargs)
|
||||||
|
if code not in (200, 204):
|
||||||
|
raise RuntimeError(f"OpenBao operation {path.split('/')[-1]} returned HTTP {code}")
|
||||||
|
return body
|
||||||
|
|
||||||
|
|
||||||
|
def root_token():
|
||||||
|
data = json.loads(INIT.read_text(encoding="utf-8"))
|
||||||
|
return data["root_token"]
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for_listener(endpoint):
|
||||||
|
for attempt in range(15):
|
||||||
|
try:
|
||||||
|
return required(endpoint)
|
||||||
|
except OSError:
|
||||||
|
if attempt == 14:
|
||||||
|
raise RuntimeError("OpenBao listener did not become ready") from None
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
|
||||||
|
def unseal():
|
||||||
|
if not wait_for_listener("sys/seal-status")["sealed"]:
|
||||||
|
print("OpenBao is already unsealed.")
|
||||||
|
return
|
||||||
|
data = json.loads(INIT.read_text(encoding="utf-8"))
|
||||||
|
response = required("sys/unseal", method="PUT", data={"key": data["keys_base64"][0]})
|
||||||
|
if response["sealed"]:
|
||||||
|
raise RuntimeError("OpenBao still sealed")
|
||||||
|
print("OpenBao unsealed by operator.")
|
||||||
|
|
||||||
|
|
||||||
|
def initialize():
|
||||||
|
initialized = wait_for_listener("sys/init")["initialized"]
|
||||||
|
if not initialized:
|
||||||
|
if INIT.exists():
|
||||||
|
raise RuntimeError("Existing operator recovery file belongs to a different store")
|
||||||
|
data = required("sys/init", method="PUT", data={"secret_shares": 1, "secret_threshold": 1}, timeout=45)
|
||||||
|
write(INIT, json.dumps(data), 0o600)
|
||||||
|
print("OpenBao initialized. Recovery material saved in the operator directory.")
|
||||||
|
unseal()
|
||||||
|
|
||||||
|
|
||||||
|
def update_role(role, folder, token):
|
||||||
|
leaf = (folder / "tls.crt").read_text(encoding="ascii")
|
||||||
|
policy = (ROOT / "infra/openbao/service-policy.hcl").read_text(encoding="ascii").replace("{role}", role)
|
||||||
|
policy_name = "worker-" + certificate_serial(folder) if role == "worker" else role
|
||||||
|
required("sys/policies/acl/" + policy_name, method="PUT", token=token, data={"policy": policy})
|
||||||
|
required("auth/cert/certs/" + role, method="POST", token=token, data={
|
||||||
|
"certificate": leaf, "allowed_dns_sans": [role + "-client"], "token_policies": [policy_name],
|
||||||
|
"token_ttl": "45s", "token_max_ttl": "45s", "token_explicit_max_ttl": "45s",
|
||||||
|
"token_no_default_policy": True,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def initial_value(name):
|
||||||
|
return (OPERATOR / "initial" / name).read_text(encoding="ascii").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def initial_bundle(role):
|
||||||
|
conf = {"database_url": db_url("lab_" + role, initial_value("db_" + role))}
|
||||||
|
if role != "jobs":
|
||||||
|
conf.update(s3_access_key_id=initial_value(f"s3_{role}_user"),
|
||||||
|
s3_secret_access_key=initial_value(f"s3_{role}_key"))
|
||||||
|
if role == "api":
|
||||||
|
conf.update(cursor_secret=initial_value("cursor_secret"), cache_url=redis_url(
|
||||||
|
"sessions", initial_value("session_password"), "valkey", 6379))
|
||||||
|
if role == "dispatcher":
|
||||||
|
conf["broker_url"] = redis_url("producer", initial_value("queue_dispatcher"), "broker", 6379)
|
||||||
|
if role == "worker":
|
||||||
|
conf["broker_url"] = redis_url("consumer", initial_value("queue_worker"), "broker", 6380)
|
||||||
|
return conf
|
||||||
|
|
||||||
|
|
||||||
|
def provision():
|
||||||
|
token = root_token()
|
||||||
|
if "lab/" not in required("sys/mounts", token=token):
|
||||||
|
required("sys/mounts/lab", method="POST", token=token, data={"type": "kv", "options": {"version": "2"}})
|
||||||
|
if "cert/" not in required("sys/auth", token=token):
|
||||||
|
required("sys/auth/cert", method="POST", token=token, data={"type": "cert"})
|
||||||
|
if "local/" not in required("sys/audit", token=token):
|
||||||
|
raise RuntimeError("OpenBao declarative audit device is unavailable")
|
||||||
|
for role in ROLE_NAMES:
|
||||||
|
update_role(role, PRIVATE / "tls" / (role + "-client"), token)
|
||||||
|
code, _ = request("lab/data/" + role, token=token)
|
||||||
|
if code == 404:
|
||||||
|
required("lab/data/" + role, method="POST", token=token, data={"options": {"cas": 0}, "data": initial_bundle(role)})
|
||||||
|
elif code != 200:
|
||||||
|
raise RuntimeError(f"OpenBao could not inspect the {role} bundle")
|
||||||
|
print("OpenBao audit, pinned service identities and scoped KV policies are ready.")
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args, data=None):
|
||||||
|
payload = data.encode("utf-8") if data is not None else None
|
||||||
|
process = subprocess.run(["docker", "compose", *args], input=payload, capture_output=True,
|
||||||
|
cwd=ROOT, timeout=100)
|
||||||
|
if process.returncode:
|
||||||
|
raise RuntimeError("Docker Compose operation failed: " + args[0] + ". See service state.")
|
||||||
|
return process.stdout.decode("utf-8", errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
def certificate_serial(folder):
|
||||||
|
serial = openssl("x509", "-in", folder / "tls.crt", "-serial", "-noout").decode().strip().split("=", 1)[1]
|
||||||
|
return format(int(serial, 16), "x")
|
||||||
|
|
||||||
|
|
||||||
|
def verify_worker_lease_token(folder):
|
||||||
|
return required("auth/cert/login", method="POST", data={"name": "worker"}, folder=folder)["auth"]
|
||||||
|
|
||||||
|
|
||||||
|
def rotate_worker():
|
||||||
|
token = root_token()
|
||||||
|
folder = PRIVATE / "tls/worker-client"
|
||||||
|
journal = ROTATION / "operation.json"
|
||||||
|
old = PRIVATE / "audit/old-worker"
|
||||||
|
staged = ROTATION / "new"
|
||||||
|
if not journal.exists():
|
||||||
|
old_bundle = required("lab/data/worker", token=token)["data"]
|
||||||
|
former = verify_worker_lease_token(folder)
|
||||||
|
old.mkdir(mode=0o755, exist_ok=True)
|
||||||
|
for file in ("tls.crt", "tls.key"):
|
||||||
|
write(old / file, (folder / file).read_bytes())
|
||||||
|
password = secrets.token_hex(32)
|
||||||
|
data = old_bundle["data"] | {"database_url": db_url("lab_worker", password),
|
||||||
|
"s3_secret_access_key": secrets.token_hex(32)}
|
||||||
|
client("worker", staged, replace=True)
|
||||||
|
write(journal, json.dumps({"old_bundle": old_bundle, "old_token": former["client_token"],
|
||||||
|
"old_policy": "worker-" + certificate_serial(folder), "new": data,
|
||||||
|
"db_password": password}), 0o600)
|
||||||
|
work = json.loads(journal.read_text(encoding="utf-8"))
|
||||||
|
old_bundle, former, data, password = (work[k] for k in ("old_bundle", "old_token", "new", "db_password"))
|
||||||
|
serial = certificate_serial(old)
|
||||||
|
if not re.fullmatch("[0-9a-f]{1,32}", serial):
|
||||||
|
raise RuntimeError("Invalid worker serial")
|
||||||
|
revoked = PRIVATE / "revocation/serials"
|
||||||
|
existing = revoked.read_text(encoding="ascii").split()
|
||||||
|
write(revoked, "\n".join(dict.fromkeys([*existing, serial])) + "\n")
|
||||||
|
current = required("lab/data/worker", token=token)["data"]
|
||||||
|
if current["data"] != data:
|
||||||
|
if current["metadata"]["version"] != old_bundle["metadata"]["version"]:
|
||||||
|
raise RuntimeError("Concurrent worker KV change. Inspect the operator rotation journal.")
|
||||||
|
required("auth/cert/certs/worker", method="DELETE", token=token)
|
||||||
|
# Remove the policy itself so every token issued to this leaf loses
|
||||||
|
# KV rights immediately, even if the token is still within its TTL.
|
||||||
|
required("sys/policies/acl/" + work["old_policy"], method="DELETE", token=token)
|
||||||
|
code, _ = request("auth/token/revoke", method="POST", token=token, data={"token": former})
|
||||||
|
if code not in (204, 400, 404):
|
||||||
|
raise RuntimeError(f"OpenBao token revocation returned HTTP {code}")
|
||||||
|
print("Prior worker KV policy removed; probe token revoked or already expired.")
|
||||||
|
old_status, _ = request("lab/data/worker", token=former, folder=old)
|
||||||
|
if old_status != 403:
|
||||||
|
raise RuntimeError(f"Old worker token returned unexpected HTTP {old_status}")
|
||||||
|
print("Old worker token rejected on KV read (403).")
|
||||||
|
sql = (f"ALTER ROLE lab_worker PASSWORD '{password}';\n"
|
||||||
|
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='lab_worker';\n")
|
||||||
|
compose("exec", "-T", "db", "psql", "-Xq", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger", data=sql)
|
||||||
|
compose("run", "--rm", "--no-deps", "-T", "s3-init", "rotate-worker",
|
||||||
|
data=data["s3_access_key_id"] + "\n" + data["s3_secret_access_key"] + "\n")
|
||||||
|
required("lab/data/worker", method="POST", token=token,
|
||||||
|
data={"options": {"cas": old_bundle["metadata"]["version"]}, "data": data})
|
||||||
|
old_status, _ = request("lab/data/worker", token=former, folder=old)
|
||||||
|
if old_status != 403:
|
||||||
|
raise RuntimeError(f"Old worker token returned unexpected HTTP {old_status}")
|
||||||
|
|
||||||
|
update_role("worker", staged, token)
|
||||||
|
for file in ("tls.crt", "tls.key"):
|
||||||
|
write(folder / file, (staged / file).read_bytes())
|
||||||
|
|
||||||
|
login_status, _ = request("auth/cert/login", method="POST", data={"name": "worker"}, folder=old)
|
||||||
|
if login_status not in (400, 403):
|
||||||
|
raise RuntimeError(f"Old worker certificate returned unexpected OpenBao HTTP {login_status}")
|
||||||
|
print(f"Old worker certificate denied for OpenBao login ({login_status}).")
|
||||||
|
verify_worker_lease_token(folder)
|
||||||
|
print(compose("--profile", "audit", "run", "--rm", "--no-deps", "-T", "audit", "security-probe", "worker",
|
||||||
|
data=json.dumps({"old": old_bundle["data"], "attachment": ""})).strip())
|
||||||
|
compose("restart", "--no-deps", "worker")
|
||||||
|
journal.unlink()
|
||||||
|
for file in ("tls.crt", "tls.key"):
|
||||||
|
(old / file).unlink()
|
||||||
|
for file in ("tls.crt", "tls.key", "ca.crt"):
|
||||||
|
(staged / file).unlink()
|
||||||
|
print("New worker certificate, DB password and S3 key activated without rebuilding.")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("action", choices=("init", "unseal", "provision", "rotate-worker"))
|
||||||
|
args = parser.parse_args()
|
||||||
|
{"init": initialize, "unseal": unseal, "provision": provision, "rotate-worker": rotate_worker}[args.action]()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
"""Create local PKI and initial credentials. Print names and status only."""
|
||||||
|
import csv
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import secrets
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
PRIVATE = ROOT / "secrets"
|
||||||
|
OPERATOR = PRIVATE / "operator"
|
||||||
|
CA_DIR = OPERATOR / "ca"
|
||||||
|
CA = CA_DIR / "ca.crt"
|
||||||
|
KEY = CA_DIR / "ca.key"
|
||||||
|
OPENSSL = os.environ.get("OPENSSL", "openssl")
|
||||||
|
REQ_CONFIG = "[req]\ndistinguished_name = dn\n[dn]\n"
|
||||||
|
|
||||||
|
SERVER_NAMES = {
|
||||||
|
"ingress": "DNS:localhost,IP:127.0.0.1",
|
||||||
|
"api-server": "DNS:api",
|
||||||
|
"db": "DNS:db",
|
||||||
|
"valkey": "DNS:valkey",
|
||||||
|
"broker": "DNS:broker",
|
||||||
|
"collector": "DNS:otel-collector",
|
||||||
|
"prometheus": "DNS:prometheus",
|
||||||
|
"loki": "DNS:loki",
|
||||||
|
"tempo": "DNS:tempo",
|
||||||
|
"s3": "DNS:s3",
|
||||||
|
"minio": "DNS:minio",
|
||||||
|
"openbao": "DNS:openbao,DNS:localhost,IP:127.0.0.1",
|
||||||
|
"grafana": "DNS:grafana,DNS:localhost,IP:127.0.0.1",
|
||||||
|
}
|
||||||
|
CLIENT_NAMES = ("api", "lb", "dispatcher", "worker", "jobs", "collector", "prometheus", "grafana", "audit", "operator")
|
||||||
|
|
||||||
|
|
||||||
|
def write(path, value, mode=0o644):
|
||||||
|
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
fd, tmp = tempfile.mkstemp(dir=path.parent)
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, "wb") as f:
|
||||||
|
f.write(value.encode() if isinstance(value, str) else value)
|
||||||
|
os.chmod(tmp, mode)
|
||||||
|
os.replace(tmp, path)
|
||||||
|
finally:
|
||||||
|
Path(tmp).unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def keep(path, value, mode=0o644):
|
||||||
|
if not path.exists():
|
||||||
|
write(path, value, mode)
|
||||||
|
return path.read_text(encoding="utf-8").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def openssl(*args, cwd=None):
|
||||||
|
proc = subprocess.run([OPENSSL, *map(str, args)], cwd=cwd, capture_output=True)
|
||||||
|
if proc.returncode:
|
||||||
|
raise SystemExit(f"OpenSSL {args[0]} failed. Check the binary and local permissions.")
|
||||||
|
return proc.stdout
|
||||||
|
|
||||||
|
|
||||||
|
def make_ca(folder, name):
|
||||||
|
if (folder / "ca.crt").exists() and (folder / "ca.key").exists():
|
||||||
|
return
|
||||||
|
folder.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
with tempfile.TemporaryDirectory(dir=folder) as tmp:
|
||||||
|
Path(tmp, "req.cnf").write_text(REQ_CONFIG, encoding="ascii")
|
||||||
|
openssl("req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-noenc",
|
||||||
|
"-config", "req.cnf", "-days", "365", "-sha256", "-keyout", "key", "-out", "cert", "-subj", f"/CN={name}",
|
||||||
|
"-addext", "basicConstraints=critical,CA:TRUE,pathlen:0",
|
||||||
|
"-addext", "keyUsage=critical,keyCertSign,cRLSign", cwd=tmp)
|
||||||
|
write(folder / "ca.key", (Path(tmp) / "key").read_bytes(), 0o600)
|
||||||
|
write(folder / "ca.crt", (Path(tmp) / "cert").read_bytes())
|
||||||
|
|
||||||
|
|
||||||
|
def issue(folder, name, san, purpose, ca_folder=CA_DIR, days=7, replace=False):
|
||||||
|
if not replace and all((folder / f).is_file() for f in ("tls.crt", "tls.key", "ca.crt")):
|
||||||
|
return
|
||||||
|
folder.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
with tempfile.TemporaryDirectory(dir=folder) as tmp:
|
||||||
|
Path(tmp, "req.cnf").write_text(REQ_CONFIG, encoding="ascii")
|
||||||
|
openssl("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-noenc",
|
||||||
|
"-config", "req.cnf", "-keyout", "key", "-out", "req", "-subj", f"/CN={name}", cwd=tmp)
|
||||||
|
Path(tmp, "ext").write_text(
|
||||||
|
f"basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage={purpose}\n"
|
||||||
|
f"subjectAltName={san}\n", encoding="ascii")
|
||||||
|
openssl("x509", "-req", "-in", "req", "-CA", ca_folder / "ca.crt", "-CAkey", ca_folder / "ca.key",
|
||||||
|
"-set_serial", "0x" + secrets.token_hex(16), "-days", days, "-sha256",
|
||||||
|
"-out", "cert", "-extfile", "ext", cwd=tmp)
|
||||||
|
write(folder / "tls.key", (Path(tmp) / "key").read_bytes())
|
||||||
|
write(folder / "tls.crt", (Path(tmp) / "cert").read_bytes())
|
||||||
|
write(folder / "ca.crt", CA.read_bytes())
|
||||||
|
if name in ("ingress", "lb-client"):
|
||||||
|
write(folder / "tls.pem", (folder / "tls.crt").read_bytes() + (folder / "tls.key").read_bytes())
|
||||||
|
|
||||||
|
|
||||||
|
def client(name, folder=None, replace=False):
|
||||||
|
return issue(folder or PRIVATE / "tls" / (name + "-client"), name + "-client", "DNS:" + name + "-client",
|
||||||
|
"clientAuth", replace=replace)
|
||||||
|
|
||||||
|
|
||||||
|
def db_url(role, password):
|
||||||
|
return (f"postgres://{role}:{password}@db:5432/messenger?"
|
||||||
|
"sslmode=verify-full&sslrootcert=/run/lab-tls/ca.crt")
|
||||||
|
|
||||||
|
|
||||||
|
def redis_url(role, password, host, port):
|
||||||
|
return f"rediss://{role}:{password}@{host}:{port}/0"
|
||||||
|
|
||||||
|
|
||||||
|
def grafana_sources():
|
||||||
|
folder = PRIVATE / "tls/grafana-client"
|
||||||
|
template = (ROOT / "infra/otel/grafana/provisioning/datasources/lab.yml").read_text(encoding="utf-8")
|
||||||
|
secure = "\n".join(f" {name}: {json.dumps((folder / file).read_text(encoding='ascii'))}"
|
||||||
|
for name, file in (("tlsCACert", "ca.crt"), ("tlsClientCert", "tls.crt"), ("tlsClientKey", "tls.key")))
|
||||||
|
write(PRIVATE / "grafana/datasources/lab.yml", template.replace(" # TLS_MATERIAL", " secureJsonData:\n" + secure))
|
||||||
|
|
||||||
|
|
||||||
|
def protect_operator():
|
||||||
|
OPERATOR.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
if os.name != "nt":
|
||||||
|
OPERATOR.chmod(0o700)
|
||||||
|
return
|
||||||
|
identity = subprocess.run(["whoami", "/user", "/fo", "csv", "/nh"], check=True, capture_output=True, text=True)
|
||||||
|
sid = next(csv.reader(identity.stdout.splitlines()))[1]
|
||||||
|
subprocess.run(["icacls", str(OPERATOR), "/inheritance:r", "/grant:r", "*" + sid + ":(OI)(CI)F"],
|
||||||
|
check=True, capture_output=True)
|
||||||
|
|
||||||
|
|
||||||
|
def bootstrap():
|
||||||
|
os.umask(0o077)
|
||||||
|
PRIVATE.mkdir(mode=0o700, exist_ok=True)
|
||||||
|
protect_operator()
|
||||||
|
make_ca(CA_DIR, "Lab7 local CA")
|
||||||
|
for name, san in SERVER_NAMES.items():
|
||||||
|
issue(PRIVATE / "tls" / name, name, san, "serverAuth")
|
||||||
|
minio = PRIVATE / "tls/minio"
|
||||||
|
(minio / "CAs").mkdir(exist_ok=True)
|
||||||
|
write(minio / "public.crt", (minio / "tls.crt").read_bytes())
|
||||||
|
write(minio / "private.key", (minio / "tls.key").read_bytes())
|
||||||
|
for name in CLIENT_NAMES:
|
||||||
|
folder = OPERATOR / "tls" if name == "operator" else None
|
||||||
|
client(name, folder)
|
||||||
|
shutil.copyfile(CA, PRIVATE / "ca.crt")
|
||||||
|
keep(PRIVATE / "revocation/serials", "")
|
||||||
|
initial = OPERATOR / "initial"
|
||||||
|
for name in ("postgres", "db_api", "db_dispatcher", "db_worker", "db_jobs", "session_password", "queue_dispatcher",
|
||||||
|
"queue_worker", "cursor_secret", "s3_root_password", "s3_api_key", "s3_dispatcher_key",
|
||||||
|
"s3_worker_key", "grafana_password"):
|
||||||
|
keep(initial / name, secrets.token_hex(32), 0o600)
|
||||||
|
for role in ("api", "dispatcher", "worker", "root"):
|
||||||
|
keep(initial / f"s3_{role}_user", role + "_" + secrets.token_hex(8), 0o600)
|
||||||
|
for name in ("postgres", "db_api", "db_dispatcher", "db_worker", "db_jobs"):
|
||||||
|
keep(PRIVATE / "db" / name, (initial / name).read_text())
|
||||||
|
keep(PRIVATE / "migrate_url", db_url("messenger", (initial / "postgres").read_text().strip()))
|
||||||
|
for name in ("s3_root_user", "s3_root_password", "grafana_password"):
|
||||||
|
keep(PRIVATE / name, (initial / name).read_text())
|
||||||
|
session = (initial / "session_password").read_text().strip()
|
||||||
|
keep(PRIVATE / "acl/sessions", "user default off\n"
|
||||||
|
f"user sessions on >{session} ~sess:* ~limit:* +ping +get +set +del +incr +expire +ttl +eval +evalsha\n")
|
||||||
|
dispatcher, worker = ((initial / f"queue_{r}").read_text().strip() for r in ("dispatcher", "worker"))
|
||||||
|
keep(PRIVATE / "acl/broker", "user default off\n"
|
||||||
|
f"user producer on >{dispatcher} ~attachment-jobs +ping +xadd\n"
|
||||||
|
f"user consumer on >{worker} ~attachment-jobs +ping +xgroup|create +xautoclaim +xreadgroup +xack +xdel +eval +evalsha\n")
|
||||||
|
grafana_sources()
|
||||||
|
probe = PRIVATE / "audit"
|
||||||
|
make_ca(OPERATOR / "foreign-ca", "Lab7 negative control CA")
|
||||||
|
issue(probe / "foreign", "foreign", "DNS:lb-client", "clientAuth", OPERATOR / "foreign-ca")
|
||||||
|
client("audit", probe / "wrong-role")
|
||||||
|
client("lb", probe / "lb", False)
|
||||||
|
operator_material = PRIVATE / "s3-setup"
|
||||||
|
for role in ("api", "dispatcher", "worker"):
|
||||||
|
keep(operator_material / (role + "_user"), (initial / f"s3_{role}_user").read_text())
|
||||||
|
keep(operator_material / (role + "_key"), (initial / f"s3_{role}_key").read_text())
|
||||||
|
for folder in (PRIVATE / "audit", PRIVATE / "tls", PRIVATE / "grafana"):
|
||||||
|
for subfolder in folder.rglob("*"):
|
||||||
|
if subfolder.is_dir():
|
||||||
|
subfolder.chmod(0o755)
|
||||||
|
folder.chmod(0o755)
|
||||||
|
for folder in ("db", "revocation", "acl", "s3-setup"):
|
||||||
|
(PRIVATE / folder).chmod(0o755)
|
||||||
|
env_path = ROOT / ".env"
|
||||||
|
if not env_path.exists():
|
||||||
|
write(env_path, (ROOT / ".env.example").read_bytes())
|
||||||
|
for name in ("restart.sh", "stop-one.sh"):
|
||||||
|
(ROOT / "scripts" / name).chmod(0o755)
|
||||||
|
print("Created local PKI and credentials. Existing values preserved.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
bootstrap()
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
@echo off
|
||||||
|
python "%~dp0stack_action.py" restart
|
||||||
Executable
+2
@@ -0,0 +1,2 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
exec python3 "$(dirname "$0")/stack_action.py" restart
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Operator hook for the unmodified public restart and failover scenarios."""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from bao import PRIVATE, ROOT, compose, unseal
|
||||||
|
|
||||||
|
|
||||||
|
def inspect(ids):
|
||||||
|
command = ["docker", "inspect", "--format",
|
||||||
|
'{{json .Config.Hostname}} {{json .State.StartedAt}} {{json .State.Status}} {{json .Id}}', *ids]
|
||||||
|
result = subprocess.run(command, check=True, text=True, capture_output=True, cwd=ROOT)
|
||||||
|
return [json.loads("[" + ",".join(line.split()) + "]") for line in result.stdout.splitlines()]
|
||||||
|
|
||||||
|
|
||||||
|
def save(name, data):
|
||||||
|
directory = PRIVATE / "runtime"
|
||||||
|
directory.mkdir(exist_ok=True)
|
||||||
|
(directory / name).write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def restart():
|
||||||
|
stores = ("db", "valkey", "broker-store", "minio", "openbao",
|
||||||
|
"prometheus-engine", "loki-engine", "tempo-engine", "grafana")
|
||||||
|
processes = ("api", "worker", "dispatcher", "lb", "collector-engine")
|
||||||
|
ids = compose("ps", "-q", *stores, *processes).split()
|
||||||
|
save("restart-before.json", inspect(ids))
|
||||||
|
compose("restart", "--no-deps", *stores)
|
||||||
|
unseal()
|
||||||
|
compose("restart", "--no-deps", *processes)
|
||||||
|
save("restart-after.json", inspect(ids))
|
||||||
|
|
||||||
|
|
||||||
|
def stop_one(target=None):
|
||||||
|
target = target or os.environ["TARGET_INSTANCE_ID"]
|
||||||
|
for node in inspect(compose("ps", "-q", "api").split()):
|
||||||
|
if node[0] == target and node[2] == "running":
|
||||||
|
save("stop-before.json", node)
|
||||||
|
subprocess.run(["docker", "stop", "--time", "7", node[3]], check=True, capture_output=True, cwd=ROOT)
|
||||||
|
save("stop-after.json", inspect([node[3]])[0])
|
||||||
|
return
|
||||||
|
raise RuntimeError("requested instance was not a running API replica")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
{"restart": restart, "stop-one": stop_one}[sys.argv[1]]()
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
@echo off
|
||||||
|
python "%~dp0stack_action.py" stop-one
|
||||||
Executable
+2
@@ -0,0 +1,2 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
exec python3 "$(dirname "$0")/stack_action.py" stop-one
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Сканирование зависимостей и образов
|
||||||
|
|
||||||
|
Проверки проведены на linux/amd64-образах на учебном хосте. Для Go полезно различать находки в модульном графе и в коде развернутого бинарника. Сначала `govulncheck` проверил Linux-граф исходной сборки. Поскольку локальный Go 1.26.0 тоже давал находки в стандартной библиотеке, runtime-версию проверяли по бинарнику из Docker.
|
||||||
|
|
||||||
|
Проверка выявила унаследованные OTLP transport и SDK с достижимыми символами, в том числе ограничения атрибутов и инициализацию SDK. Lab7 обновляет SDK до 1.47.0 и связанный log exporter до 0.23.0. Обновлены pgx и go-redis, версия grpc в графе поднята до 1.83.2. Сборка API и worker перешла на Go 1.27.4 с исправлениями net/http и toolchain. [GO-2026-6974](https://pkg.go.dev/vuln/GO-2026-6974) · [GO-2026-4394](https://pkg.go.dev/vuln/GO-2026-4394) · [Go release history](https://go.dev/doc/devel/release)
|
||||||
|
|
||||||
|
Скан бинарника после первого обновления ещё находил связанные символы модуля `klauspost/compress` 1.19.2. Модуль поднят до 1.20.2. Повторный `govulncheck -mode binary` для финальной Linux-сборки вывел `No vulnerabilities found.`. Это результат проверки зарегистрированных advisories на момент прогона. [GO-2026-6865](https://pkg.go.dev/vuln/GO-2026-6865)
|
||||||
|
|
||||||
|
Образы сканировались Trivy 0.65.0. Публичная БД была скачана отдельным запуском. Проверка архивов выполнялась в контейнере с `--network none`, без доступа к Docker socket и без передачи образов облачному сканеру.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
mkdir -p scan/cache
|
||||||
|
docker run --rm -v "$PWD/scan/cache:/cache" aquasec/trivy:0.65.0 image --cache-dir /cache --download-db-only
|
||||||
|
docker image save mtusi-messenger-worker:lab7 -o scan/worker.tar
|
||||||
|
docker run --rm --network none -v "$PWD/scan:/scan" aquasec/trivy:0.65.0 image \
|
||||||
|
--cache-dir /scan/cache --skip-db-update --skip-java-db-update --offline-scan \
|
||||||
|
--scanners vuln --input /scan/worker.tar
|
||||||
|
docker compose cp --index 1 api:/messenger scan/api.bin
|
||||||
|
govulncheck -mode binary scan/api.bin
|
||||||
|
```
|
||||||
|
|
||||||
|
Индекс в команде выбирает первую API-реплику. Сохранённые архивы и полные JSON сканера предназначены для локального анализа.
|
||||||
|
|
||||||
|
| Находка | Применимость на стенде |
|
||||||
|
| --- | --- |
|
||||||
|
| CVE-2026-31789, OpenSSL в Alpine | Advisory ограничивает этот переполненный расчёт 32-битными системами. Проверенный хост и образы — amd64. Аптечный TLS-пакет всё равно требует обновления при переносе на другую архитектуру. [OpenSSL](https://openssl-library.org/news/vulnerabilities/) |
|
||||||
|
| CVE-2025-58050, PCRE2 в HAProxy | Путь требует специальной конструкции внутри регулярного выражения. HAProxy на этом стенде принимает из запросов только значения, конфигурация входа и backend health check задаётся оператором. Оценка касается конфигурации Lab7. [PCRE2 advisory](https://github.com/PCRE2Project/pcre2/security/advisories/GHSA-c2gv-xgf5-5cc2) |
|
||||||
|
| CVE-2026-41145, MinIO | Уязвимый режим streaming unsigned trailer запрещён TLS-шлюзом S3. MinIO доступен по своей отдельной сети только шлюзу. Известный путь ограничен конфигурацией. Использован архивный CE, у которого остаются собственные и транзитивные риски. [MinIO advisory](https://github.com/minio/minio/security/advisories/GHSA-hv4r-mvr4-25vw) |
|
||||||
|
| CVE-2026-33322, CVE-2026-33419, CVE-2026-34204, CVE-2026-39414, CVE-2026-40344 в MinIO | OIDC и LDAP выключены. Шлюз запрещает заголовок репликации, S3 Select и unsigned trailer. Это компенсирующие ограничения для архивного CE. |
|
||||||
|
| CVE-2026-116587, go-jose в OpenBao 2.7.3 | Находка отмечена для двух версий модуля. На стенде используется cert auth, KV и декларативный аудит. Парсинг предоставляемых клиентом JWK через OIDC/JWT auth не задействован. |
|
||||||
|
| CVE-2026-33815/33816, CVE-2026-77405/77408/77411, CVE-2026-33186 в Collector | Сборка contrib включает pgx, RabbitMQ и gRPC. Здесь нет PostgreSQL/AMQP extension, receiver или exporter. OTLP и health/scrape обслуживаются по HTTP, gRPC listener и gRPC authz в Collector не настроены. Направления и обработчики указаны в [матрице](TRUST_MATRIX.md). |
|
||||||
|
| CVE-2025-68121, Go TLS в образе Collector | Закрытый receiver Collector принимает локальный HTTP от TLS-шлюза. На серверной стороне шлюза отключены session tickets. Экспорт идёт к тем же шлюзам, которые также отключают tickets. |
|
||||||
|
| CVE-2025-7458, SQLite в базовом образе worker | Уязвимость требует возможности выполнять произвольные SQL-выражения в SQLite. Worker использует PostgreSQL с фиксированными параметризованными запросами, а Pillow получает JPEG/PNG. SQLite не используется в этом потоке. [Debian tracker](https://security-tracker.debian.org/tracker/CVE-2025-7458) |
|
||||||
|
| CVE-2023-45853, zlib в базовом образе worker | Уязвимый contrib MiniZip не входит в сборку zlib этой версии Bookworm. Код передачи изображений не поддерживает загрузку ZIP. [Debian tracker](https://security-tracker.debian.org/tracker/CVE-2023-45853) |
|
||||||
|
|
||||||
|
Trivy не нашёл уязвимых пакетов в итоговом scratch-образе API. Для worker он показал 2 critical из базового Bookworm и 49 high. После обновления OpenBao с 2.4.4 до 2.7.3 число находок по образу снизилось с 263 до 19. Для итогового образа Trivy показал 0 critical и 2 high. Старый архив MinIO показал 6 critical и 43 high, Collector — 7 и 73, HAProxy — 3 и 28. Эти числа учитывают зависимости независимо от применимости. Прогоны Trivy для Grafana и Loki упёрлись в память Docker Desktop при распаковке слоёв. Разбор охватывает перечисленные завершённые сканы. [OpenBao 2.7 release notes](https://openbao.org/community/release-notes/2-7-0/)
|
||||||
@@ -1,19 +1,25 @@
|
|||||||
# Модель угроз — заполнить
|
# Модель угроз Lab7
|
||||||
|
|
||||||
## Активы и акторы
|
## Активы и акторы
|
||||||
|
|
||||||
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда.
|
Защищаем пароли и сессии, историю сообщений, принадлежность вложений, принятые задания, идентичности сервисов и ключ CA. Телеметрия содержит маршруты, длительность, статусы и технические идентификаторы. Приглашённый участник знает токен своей сессии. Посторонний зарегистрированный пользователь может отправлять запросы через входной HTTPS и знать UUID чужого вложения. Скомпрометированный worker в эксперименте получает свою учётную запись, сетевую видимость обычного worker и его рабочий KV-пакет. Оператор контролирует Compose и PKI. Компрометация оператора, Docker Engine или ОС хоста выходит за пределы эксперимента.
|
||||||
|
|
||||||
## Границы доверия
|
## Границы доверия
|
||||||
|
|
||||||
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача.
|
Клиент доверяет локальному CA и имени ingress. API принимает сертификаты LB и проверяет Bearer сессию отдельно от транспортной идентичности. Valkey хранит только SHA-256 сессионного токена и TTL. PostgreSQL и MinIO разделяют права API, dispatcher и worker. Broker разрешает только соответствующую mTLS identity и ACL. OpenBao выдаёт токены на основе заранее зарегистрированных сертификатов. Порты OpenBao и Grafana опубликованы только на loopback хоста. Разрешённые сетевые переходы и локальные hops описаны в [матрице доверия](TRUST_MATRIX.md).
|
||||||
|
|
||||||
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
|
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
|
||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO | TODO |
|
| Подмена ingress или подключение по неверному имени | Клиент знает, куда передаёт Bearer или Basic | Обязательная проверка CA и SAN | Публичный `tests/security.py` и тест имени в `audit` | Компрометация локального CA затрагивает его клиентов |
|
||||||
|
| Прямое подключение к API с другим сертификатом того же CA | Запрос входит через доверенный ingress | Закрытый порт, проверка client chain и DNS SAN `lb-client` | `audit` обращается к каждой реплике с тремя неверными вариантами | Скомпрометированный LB может пересылать запросы, Bearer проверяет API |
|
||||||
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
| Попытка прочитать вложение другого чата или использовать его UUID в своём сообщении | ACL распространяется на метаданные, бинарные ответы и привязку | Проверка членства и совпадения chat ID в PostgreSQL | `student-tests/security.py security` проверяет 404 и поддельный `X-User-Id` | Член чата может сохранить выданные ему файлы |
|
||||||
|
| Перебор пароля или насыщение Argon2 через обе реплики | Работа KDF ограничена даже при смене реплики | Общие окна Valkey, слоты KDF и лимиты тела | Семь запросов одной учетной записи через обе реплики, проверка 429 и `Retry-After` | Глобальное окно может временно ограничить легитимные попытки |
|
||||||
|
| Повтор токена после logout или expiry | Сессию можно отозвать | SHA-256 ключ, удаление, TTL и проверка времени | `security` и `expiry` | Действующий токен предоставляет права владельца до отзыва |
|
||||||
|
| Штатная identity пытается получить секреты другой роли | Worker получает только собственные права | Pinned leaf OpenBao и отдельная KV policy | Чтение своего пути проходит, чужого и запись policy дают 403 | В пределах срока токен может читать свой путь |
|
||||||
|
| Worker пытается прочитать сообщения, изменить владельца, записать staging или публиковать задания | Компрометация ограничена image pipeline | Ограничения на столбцы PostgreSQL, префиксы S3 и команды/ключ Valkey | `student-tests/security.py track` | Worker видит staging и может менять относящиеся к обработке состояния и объекты результатов |
|
||||||
|
| Чужой процесс подаёт поддельную телеметрию или пишет в источник Grafana | Путь ingest отделён от чтения | mTLS, allowlist identity и ограничения метода/маршрута | Проверки Collector и Prometheus в `audit` | Допущенный отправитель способен исказить собственные сигналы |
|
||||||
|
| Оператор запечатал OpenBao, украдена старая пара worker | Учётные данные перестают работать после предусмотренного окна | Pinned leaf, отзыв серийного номера, отзыв токенов и замена паролей. Дальнейшая работа ограничена последним успешным lease | `track`, `sealed`, новые TLS-соединения после отзыва | Один OpenBao. Затяжной отказ остановит бизнес-обработку |
|
||||||
|
|
||||||
## Lifecycle и инциденты
|
## Lifecycle и инциденты
|
||||||
|
|
||||||
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском.
|
CA private key и файл восстановления доступны оператору хоста. Контейнеры получают только собственные leaf и общий публичный CA. Начальные пароли зависимостей и операторское восстановление хранятся в отдельной локальной директории. В штатной работе приложение аутентифицируется leaf-сертификатом и получает свежий scoped токен каждые 10 с. Последняя успешная выдача разрешает работу до 45 с. Долгая недоступность OpenBao или истечение leaf останавливают процесс. После unseal контейнер переаутентифицируется. При отзыве worker старый сертификат исключается из OpenBao и шлюзов, старые токены отзываются, роли получают новые пароли PostgreSQL и S3. Разбор применимости CVE и фактические результаты находятся в [отчёте](../REPORT.md).
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Матрица доверия Lab7
|
||||||
|
|
||||||
|
Матрица реализации следует [шаблону из контракта](../contracts/trust-matrix.md). PKI стенда использует один локальный CA с ключом P-256. Срок CA — 365 дней, leaf — 7 дней. TLS 1.2+ на сетевых границах. DNS SAN проверяет имя сервера. Для разрешённых клиентов шлюзы проверяют цепочку, клиентский DNS SAN и отзыв серийного номера.
|
||||||
|
|
||||||
|
| Связь | Endpoint и идентичность | Права и время жизни | Проверка |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Клиент → HAProxy | `https://127.0.0.1:8443` или `https://localhost:8443`, IP/DNS SAN, Bearer | Сессия 3600 с по умолчанию. Basic используется для получения сессии. LB удаляет входной `X-User-Id` | Публичные smoke и TLS. Собственные `security` и `expiry` |
|
||||||
|
| HAProxy → обе реплики | `api:8080`, TLS с проверкой SAN `api` и client SAN `lb-client` | Backend API и health принимают только LB. Далее действует Bearer | `audit` проверяет каждый IP с верным, отсутствующим, чужим и same-CA запрещённым leaf |
|
||||||
|
| API, dispatcher, worker, migrate, jobs → PostgreSQL | `db:5432`, `sslmode=verify-full`, SAN `db`. Своя SCRAM-роль для каждого назначения | DDL только у migrate. Worker читает очередь и меняет только поля обработки. Пароли остаются действительными до ротации | `track` проверяет `pg_stat_ssl`, SQLSTATE 42501 и 28P01 после ротации. `pg_hba.conf` допускает TCP только через `hostssl` |
|
||||||
|
| API, dispatcher, worker → S3 → MinIO | `https://s3:9000` → `https://minio:9000`, проверка обоих SAN, разные SigV4 credentials | API пишет staging и читает готовые объекты. Dispatcher перечисляет и чистит staging. Worker читает staging, пишет и проверяет результаты. Ключи действуют до ротации | `track` проверяет reads, staging write/delete и bucket listing, затем отказ старых credentials |
|
||||||
|
| Dispatcher, worker → broker | `broker:6379` для `dispatcher-client`, `broker:6380` для `worker-client` | mTLS плюс Valkey ACL producer/consumer на `attachment-jobs`. Открытое соединение закрывается при отзыве leaf или его expiry с проверкой раз в секунду | `audit` отклоняет 3 неверных варианта сертификата. `track` проверяет PING и запреты команд, затем свежий отказ старому leaf |
|
||||||
|
| API, dispatcher, worker → Collector | `https://otel-collector:4318/v1/{metrics,logs,traces}`, mTLS с отдельными SAN трёх отправителей | Только OTLP POST. Prometheus может читать `/metrics` с `prometheus-client` | `audit`, `security` и `track` |
|
||||||
|
| Collector → Prometheus, Loki, Tempo | `https://prometheus:9090`, `https://loki:3100`, `https://tempo:3200`, mTLS `collector-client` | Только заданные OTLP POST; применяется отзыв leaf | `security` подтверждает метрики, логи и трассы. `audit` отклоняет LB и попытку ingest от observer |
|
||||||
|
| Grafana → data sources | Те же endpoint и SAN; mTLS `grafana-client` | Только пути чтения и методы PromQL, явно заданные в `gateway.go` | `security` использует все три datasource и проверяет запрет анонимного доступа |
|
||||||
|
| API, worker, dispatcher, jobs → OpenBao | `https://openbao:8200`, общий CA и pinned leaf каждой роли при auth | Один KV read path, токен 45 с, повторный вход раз в 10 с | `security` проверяет собственный/чужой путь и запись policy. `track` проверяет отзыв, `sealed` проверяет истечение |
|
||||||
|
| Оператор → OpenBao, Grafana, S3 admin | OpenBao loopback 8200 с operator leaf и отдельным root token. Grafana loopback 3443 с паролем. S3 admin через одноразовый Compose container и TLS | Операторы ведут lifecycle. Сервисам секреты оператора не монтируются | Bootstrap, `track`, проверка портов и отрицательная проверка Grafana в `security` |
|
||||||
|
| API → Valkey sessions | `valkey:6379`, native TLS, SAN `valkey`, роль `sessions` | ACL разрешает сессии и атомарные окна. Пароль из собственного KV API | `security`, `expiry`, публичный persistence |
|
||||||
|
| Межузловая репликация | Не применяется. Одна копия каждого stateful backend и две независимые API-реплики | AOF, PostgreSQL WAL и named volumes сохраняют состояние при рестарте контейнера | Публичные persistence/failover и `track` |
|
||||||
|
|
||||||
|
## Изоляция локальных переходов
|
||||||
|
|
||||||
|
- Broker, Collector, Prometheus, Loki и Tempo используют пару контейнеров с общим network namespace. Внутренний backend слушает только `127.0.0.1` этого namespace. К сервисам обращаются через TLS-порт шлюза. Готовность LB проверяется тем же mTLS, что и бизнес-API. `pg_isready` работает внутри namespace PostgreSQL и проверяет запуск сервера. Сквозная готовность API проверяет реальные TLS-клиенты PostgreSQL, Valkey и S3.
|
||||||
|
- Отдельная внутренняя сеть MinIO содержит только его сервер и S3 gateway. Для админских задач S3 действует SigV4. Секреты root монтируются в MinIO и временный `s3-init`. Консоль выключена, её порт привязан к loopback внутри контейнера.
|
||||||
|
- Bootstrap PostgreSQL использует локальный Unix socket, который доступен только в контейнере БД. Operator wrapper обращается к нему через `docker compose exec`. На TCP действует SCRAM и TLS. OpenBao audit file хранится с данными OpenBao, значения credentials записываются в HMAC-виде.
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"github.com/minio/minio-go/v7"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
)
|
||||||
|
|
||||||
|
func probeHTTP(endpoint, overrideHost, clientDir string, method string) (int, error) {
|
||||||
|
transport, err := labHTTPTransport(false)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer transport.CloseIdleConnections()
|
||||||
|
transport.TLSClientConfig.ServerName = overrideHost
|
||||||
|
if clientDir != "" {
|
||||||
|
pair, err := leaf(clientDir)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
transport.TLSClientConfig.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
||||||
|
return &pair, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
client := http.Client{Transport: transport, Timeout: 3 * time.Second}
|
||||||
|
req, err := http.NewRequest(method, endpoint, nil)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if method == "POST" {
|
||||||
|
req.Header.Set("Content-Type", "application/x-protobuf")
|
||||||
|
}
|
||||||
|
res, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
res.Body.Close()
|
||||||
|
return res.StatusCode, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func probeBroker(address, clientDir string) error {
|
||||||
|
cfg, err := clientTLS(false)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
cfg.ServerName = "broker"
|
||||||
|
if clientDir != "" {
|
||||||
|
pair, err := leaf(clientDir)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
cfg.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { return &pair, nil }
|
||||||
|
}
|
||||||
|
conn, err := tls.DialWithDialer(&net.Dialer{Timeout: 2 * time.Second}, "tcp", address, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
_ = conn.SetDeadline(time.Now().Add(2 * time.Second))
|
||||||
|
if _, err = io.WriteString(conn, "*1\r\n$4\r\nPING\r\n"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
buffer := make([]byte, 100)
|
||||||
|
n, err := conn.Read(buffer)
|
||||||
|
if strings.HasPrefix(string(buffer[:n]), "-NOAUTH") {
|
||||||
|
return nil // The TLS identity reached Valkey, which still requires its ACL password.
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return errors.New("unexpected broker response")
|
||||||
|
}
|
||||||
|
|
||||||
|
func rejectedTLS(err error) bool {
|
||||||
|
return err != nil && !os.IsTimeout(err) && strings.Contains(err.Error(), "tls")
|
||||||
|
}
|
||||||
|
|
||||||
|
func probeMatrix() error {
|
||||||
|
ips, err := net.LookupHost("api")
|
||||||
|
if err != nil || len(ips) < 2 {
|
||||||
|
return errors.New("matrix needs both API replicas")
|
||||||
|
}
|
||||||
|
for _, ip := range ips {
|
||||||
|
target := "https://" + net.JoinHostPort(ip, "8080") + "/health/live"
|
||||||
|
if code, err := probeHTTP(target, "api", "/audit/lb", "GET"); err != nil || code != 200 {
|
||||||
|
return errors.New("LB identity did not reach API replica")
|
||||||
|
}
|
||||||
|
for _, dir := range []string{"", "/audit/foreign", "/audit/wrong-role"} {
|
||||||
|
if _, err := probeHTTP(target, "api", dir, "GET"); !rejectedTLS(err) {
|
||||||
|
return errors.New("API negative peer TLS check failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := probeHTTP(target, "wrong.lab", "/audit/lb", "GET"); !rejectedTLS(err) {
|
||||||
|
return errors.New("wrong destination SAN accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Printf("API mTLS: %d replicas allow LB; missing, foreign CA, wrong identity and wrong server SAN rejected\n", len(ips))
|
||||||
|
for _, dir := range []string{"", "/audit/foreign", "/audit/wrong-role"} {
|
||||||
|
if err := probeBroker("broker:6380", dir); !rejectedTLS(err) {
|
||||||
|
return errors.New("broker negative peer TLS check failed")
|
||||||
|
}
|
||||||
|
if _, err := probeHTTP("https://otel-collector:4318/v1/logs", "", dir, "POST"); !rejectedTLS(err) {
|
||||||
|
return errors.New("Collector negative peer TLS check failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Println("Broker and Collector: missing, foreign CA and wrong same-CA identity rejected")
|
||||||
|
for _, endpoint := range []string{"https://prometheus:9090/-/ready", "https://loki:3100/ready", "https://tempo:3200/ready"} {
|
||||||
|
until := time.Now().Add(40 * time.Second)
|
||||||
|
code, err := probeHTTP(endpoint, "", tlsDir, "GET")
|
||||||
|
for err == nil && (code == 502 || code == 503) && time.Now().Before(until) {
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
code, err = probeHTTP(endpoint, "", tlsDir, "GET")
|
||||||
|
}
|
||||||
|
if err != nil || code != 200 {
|
||||||
|
return fmt.Errorf("telemetry backend reader check failed for %s (HTTP %d; %v)", endpoint, code, err)
|
||||||
|
}
|
||||||
|
if _, err := probeHTTP(endpoint, "", "/audit/lb", "GET"); !rejectedTLS(err) {
|
||||||
|
return errors.New("telemetry backend accepted LB identity")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if status, err := probeHTTP("https://prometheus:9090/api/v1/otlp/v1/metrics", "", tlsDir, "POST"); err != nil || status != 403 {
|
||||||
|
return errors.New("telemetry reader was not rejected at the ingest path")
|
||||||
|
}
|
||||||
|
fmt.Println("Telemetry storage: audit read succeeds; LB peer and reader ingest rejected")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func probeWorker() error {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
var input struct {
|
||||||
|
Attachment string `json:"attachment"`
|
||||||
|
Staging string `json:"staging"`
|
||||||
|
Old serviceSecrets `json:"old"`
|
||||||
|
}
|
||||||
|
if json.NewDecoder(os.Stdin).Decode(&input) != nil {
|
||||||
|
return errors.New("worker probe requires fixture input")
|
||||||
|
}
|
||||||
|
if input.Old.DatabaseURL != "" {
|
||||||
|
return probeOldCredentials(ctx, input.Old, input.Attachment)
|
||||||
|
}
|
||||||
|
secrets, stop, err := startSecrets("worker")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer stop()
|
||||||
|
cfg, err := databaseConfig(secrets.DatabaseURL, 1)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
var encrypted bool
|
||||||
|
err = db.QueryRow(ctx, "SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()").Scan(&encrypted)
|
||||||
|
if err != nil || !encrypted {
|
||||||
|
return errors.New("worker database TLS check failed")
|
||||||
|
}
|
||||||
|
if _, err := db.Exec(ctx, "SELECT id,state FROM image_jobs LIMIT 1"); err != nil {
|
||||||
|
return errors.New("worker queue table read denied")
|
||||||
|
}
|
||||||
|
for _, q := range []string{"SELECT password_hash FROM users LIMIT 1", "SELECT text FROM messages LIMIT 1",
|
||||||
|
"DELETE FROM image_jobs WHERE false", "UPDATE attachments SET owner_id=owner_id WHERE false"} {
|
||||||
|
_, err := db.Exec(ctx, q)
|
||||||
|
var pg *pgconn.PgError
|
||||||
|
if !errors.As(err, &pg) || pg.Code != "42501" {
|
||||||
|
return errors.New("worker database authorization check failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Println("Worker DB: TLS and job read allowed; password hashes, messages, job deletion and owner changes denied")
|
||||||
|
s3, bucket, err := s3Client(secrets)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if input.Staging != "" {
|
||||||
|
if _, err := s3.StatObject(ctx, bucket, stagingKey(input.Staging), minio.StatObjectOptions{}); err != nil {
|
||||||
|
return errors.New("worker staging read failed")
|
||||||
|
}
|
||||||
|
fmt.Println("Worker S3: staged originals readable before cleanup")
|
||||||
|
}
|
||||||
|
if _, err := s3.StatObject(ctx, bucket, resultKey(input.Attachment, 1, "original"), minio.StatObjectOptions{}); err != nil {
|
||||||
|
return errors.New("worker result read failed")
|
||||||
|
}
|
||||||
|
_, err = s3.PutObject(ctx, bucket, "staging/probe", strings.NewReader("test"), 4, minio.PutObjectOptions{})
|
||||||
|
if minio.ToErrorResponse(err).Code != "AccessDenied" {
|
||||||
|
return errors.New("worker staging write authorization check failed")
|
||||||
|
}
|
||||||
|
results := s3.ListObjects(ctx, bucket, minio.ListObjectsOptions{Recursive: true})
|
||||||
|
if minio.ToErrorResponse((<-results).Err).Code != "AccessDenied" {
|
||||||
|
return errors.New("worker bucket enumeration authorization check failed")
|
||||||
|
}
|
||||||
|
if err = s3.RemoveObject(ctx, bucket, "staging/probe", minio.RemoveObjectOptions{}); minio.ToErrorResponse(err).Code != "AccessDenied" {
|
||||||
|
return errors.New("worker staging delete authorization check failed")
|
||||||
|
}
|
||||||
|
fmt.Println("Worker S3: result reads allowed; bucket listing, staging write and delete denied")
|
||||||
|
opts, err := redisTLS(secrets.BrokerURL, true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
broker := redis.NewClient(opts)
|
||||||
|
defer broker.Close()
|
||||||
|
if err = broker.Ping(ctx).Err(); err != nil {
|
||||||
|
return errors.New("worker broker authentication failed")
|
||||||
|
}
|
||||||
|
for _, args := range [][]any{{"XADD", imageStream, "0-0", "test", "test"}, {"XRANGE", "other-stream", "-", "+"}, {"CONFIG", "GET", "port"}} {
|
||||||
|
err := broker.Do(ctx, args...).Err()
|
||||||
|
if err == nil || !strings.HasPrefix(err.Error(), "NOPERM") {
|
||||||
|
return errors.New("worker broker authorization check failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fmt.Println("Worker queue: broker login allowed; producer, unrelated stream and admin commands denied")
|
||||||
|
if status, err := probeHTTP("https://otel-collector:4318/v1/logs", "", tlsDir, "POST"); err != nil || status != 200 {
|
||||||
|
return errors.New("worker Collector ingest failed")
|
||||||
|
}
|
||||||
|
fmt.Println("Worker Collector: OTLP ingest allowed")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func probeOldCredentials(ctx context.Context, old serviceSecrets, attachment string) error {
|
||||||
|
cfg, err := databaseConfig(old.DatabaseURL, 1)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
var pg *pgconn.PgError
|
||||||
|
if err := db.Ping(ctx); !errors.As(err, &pg) || pg.Code != "28P01" {
|
||||||
|
return errors.New("old DB password was not rejected with authentication failure")
|
||||||
|
}
|
||||||
|
s3, bucket, err := s3Client(old)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
obj, err := s3.GetObject(ctx, bucket, stagingKey(attachment), minio.GetObjectOptions{})
|
||||||
|
if err == nil {
|
||||||
|
defer obj.Close()
|
||||||
|
var byteBuffer [1]byte
|
||||||
|
_, err = obj.Read(byteBuffer[:])
|
||||||
|
}
|
||||||
|
if code := minio.ToErrorResponse(err).Code; code != "SignatureDoesNotMatch" && code != "InvalidAccessKeyId" {
|
||||||
|
return errors.New("old S3 credentials were not rejected with authentication failure")
|
||||||
|
}
|
||||||
|
if err := probeBroker("broker:6380", "/audit/old-worker"); !rejectedTLS(err) {
|
||||||
|
return errors.New("old worker certificate accepted at broker")
|
||||||
|
}
|
||||||
|
if _, err := probeHTTP("https://otel-collector:4318/v1/logs", "", "/audit/old-worker", "POST"); !rejectedTLS(err) {
|
||||||
|
return errors.New("old worker certificate accepted at Collector")
|
||||||
|
}
|
||||||
|
fmt.Println("Old worker: DB password, S3 credentials and broker/Collector certificate rejected on fresh connections")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func securityProbe() error {
|
||||||
|
if len(os.Args) != 3 {
|
||||||
|
return errors.New("security-probe requires a scenario")
|
||||||
|
}
|
||||||
|
switch os.Args[2] {
|
||||||
|
case "matrix":
|
||||||
|
return probeMatrix()
|
||||||
|
case "worker":
|
||||||
|
return probeWorker()
|
||||||
|
default:
|
||||||
|
return errors.New("unknown security probe")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"embed"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed migrations/*.sql
|
||||||
|
var migrations embed.FS
|
||||||
|
|
||||||
|
func migrate(ctx context.Context, db *pgxpool.Pool) error {
|
||||||
|
conn, err := db.Acquire(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer conn.Release()
|
||||||
|
if _, err = conn.Exec(ctx, "SELECT pg_advisory_lock(202602)"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer conn.Exec(context.Background(), "SELECT pg_advisory_unlock(202602)")
|
||||||
|
if _, err = conn.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
entries, err := migrations.ReadDir("migrations")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
|
||||||
|
for _, entry := range entries {
|
||||||
|
raw, err := migrations.ReadFile("migrations/" + entry.Name())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sum := sha256.Sum256(raw)
|
||||||
|
checksum := hex.EncodeToString(sum[:])
|
||||||
|
var previous string
|
||||||
|
err = conn.QueryRow(ctx, "SELECT checksum FROM schema_migrations WHERE version=$1", entry.Name()).Scan(&previous)
|
||||||
|
if err == nil {
|
||||||
|
if previous != checksum {
|
||||||
|
return fmt.Errorf("migration checksum mismatch: %s", entry.Name())
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tx, err := conn.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err = tx.Exec(ctx, string(raw)); err == nil {
|
||||||
|
_, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version,checksum) VALUES($1,$2)", entry.Name(), checksum)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
tx.Rollback(ctx)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err = tx.Commit(ctx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func dbError(err error) error {
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return missing()
|
||||||
|
}
|
||||||
|
var pe *pgconn.PgError
|
||||||
|
if errors.As(err, &pe) {
|
||||||
|
switch pe.Code {
|
||||||
|
case "23505":
|
||||||
|
return apiError{409, "conflict", "Username already exists"}
|
||||||
|
case "23503", "23514", "22P02", "22021":
|
||||||
|
return invalid()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return unavailable()
|
||||||
|
}
|
||||||
|
func stamp(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000000Z") }
|
||||||
|
|
||||||
|
// pgx BytesScanner preserves every validated UTF-8 code point, including NUL.
|
||||||
|
type utf8String struct{ dst *string }
|
||||||
|
|
||||||
|
func (s utf8String) ScanBytes(value []byte) error {
|
||||||
|
*s.dst = string(value)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanUser(row pgx.Row) (User, error) {
|
||||||
|
var u User
|
||||||
|
var t time.Time
|
||||||
|
err := row.Scan(&u.ID, &u.Username, utf8String{&u.DisplayName}, &t)
|
||||||
|
u.CreatedAt = stamp(t)
|
||||||
|
return u, dbError(err)
|
||||||
|
}
|
||||||
|
func (a *App) user(ctx context.Context, id string) (User, error) {
|
||||||
|
return scanUser(a.db.QueryRow(ctx, "SELECT id::text,username,display_name,created_at FROM users WHERE id=$1", id))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) createChat(ctx context.Context, title string, ids []string) (Chat, error) {
|
||||||
|
c := Chat{ID: uuid(), Title: title, MemberIDs: ids}
|
||||||
|
var t time.Time
|
||||||
|
tx, err := a.db.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return c, unavailable()
|
||||||
|
}
|
||||||
|
defer tx.Rollback(ctx)
|
||||||
|
err = tx.QueryRow(ctx, "INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at", c.ID, []byte(title)).Scan(&t)
|
||||||
|
if err != nil {
|
||||||
|
return c, dbError(err)
|
||||||
|
}
|
||||||
|
// FK failure on any participant rolls back the chat and earlier participants.
|
||||||
|
for _, id := range ids {
|
||||||
|
if _, err = tx.Exec(ctx, "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", c.ID, id); err != nil {
|
||||||
|
return c, dbError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err = tx.Commit(ctx); err != nil {
|
||||||
|
return c, unavailable()
|
||||||
|
}
|
||||||
|
c.CreatedAt = stamp(t)
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
func (a *App) chat(ctx context.Context, id, user string) (Chat, error) {
|
||||||
|
c := Chat{}
|
||||||
|
var t time.Time
|
||||||
|
err := a.db.QueryRow(ctx, `SELECT c.id::text,c.title,c.created_at,
|
||||||
|
ARRAY(SELECT user_id::text FROM chat_members WHERE chat_id=c.id ORDER BY user_id)
|
||||||
|
FROM chats c WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2)`, id, user).Scan(&c.ID, utf8String{&c.Title}, &t, &c.MemberIDs)
|
||||||
|
c.CreatedAt = stamp(t)
|
||||||
|
return c, dbError(err)
|
||||||
|
}
|
||||||
|
func boundary(c cursor) (time.Time, string, error) {
|
||||||
|
if c.ID == "" {
|
||||||
|
return time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC), "00000000-0000-0000-0000-000000000000", nil
|
||||||
|
}
|
||||||
|
t, err := time.Parse(time.RFC3339Nano, c.Time)
|
||||||
|
if err != nil {
|
||||||
|
return t, "", invalid()
|
||||||
|
}
|
||||||
|
id, err := normalizeID(c.ID)
|
||||||
|
return t, id, err
|
||||||
|
}
|
||||||
|
func (a *App) history(ctx context.Context, id string, limit int, c cursor, scope string) (Page[Message], error) {
|
||||||
|
result := Page[Message]{Items: []Message{}}
|
||||||
|
t, last, err := boundary(c)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
rows, err := a.db.Query(ctx, `SELECT id::text,chat_id::text,sender_id::text,text,created_at,ARRAY(SELECT unnest(attachment_ids)::text) FROM messages
|
||||||
|
WHERE chat_id=$1 AND (created_at,id)>($2,$3) ORDER BY messages.created_at,messages.id LIMIT $4`, id, t, last, limit+1)
|
||||||
|
if err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
var m Message
|
||||||
|
var created time.Time
|
||||||
|
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, utf8String{&m.Text}, &created, &m.AttachmentIDs); err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
m.CreatedAt = stamp(created)
|
||||||
|
result.Items = append(result.Items, m)
|
||||||
|
}
|
||||||
|
if rows.Err() != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
if len(result.Items) > limit {
|
||||||
|
result.Items = result.Items[:limit]
|
||||||
|
m := result.Items[limit-1]
|
||||||
|
next := a.encodeCursor(scope, m.CreatedAt, m.ID)
|
||||||
|
result.NextCursor = &next
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
func (a *App) listChats(ctx context.Context, user string, limit int, c cursor, scope string) (Page[Chat], error) {
|
||||||
|
result := Page[Chat]{Items: []Chat{}}
|
||||||
|
t, last, err := boundary(c)
|
||||||
|
if err != nil {
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
rows, err := a.db.Query(ctx, `SELECT c.id::text,c.title,c.created_at,
|
||||||
|
ARRAY(SELECT user_id::text FROM chat_members WHERE chat_id=c.id ORDER BY user_id)
|
||||||
|
FROM chats c JOIN chat_members own ON own.chat_id=c.id AND own.user_id=$1
|
||||||
|
WHERE (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, user, t, last, limit+1)
|
||||||
|
if err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
var chat Chat
|
||||||
|
var created time.Time
|
||||||
|
if err = rows.Scan(&chat.ID, utf8String{&chat.Title}, &created, &chat.MemberIDs); err != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
chat.CreatedAt = stamp(created)
|
||||||
|
result.Items = append(result.Items, chat)
|
||||||
|
}
|
||||||
|
if rows.Err() != nil {
|
||||||
|
return result, unavailable()
|
||||||
|
}
|
||||||
|
if len(result.Items) > limit {
|
||||||
|
result.Items = result.Items[:limit]
|
||||||
|
v := result.Items[limit-1]
|
||||||
|
next := a.encodeCursor(scope, v.CreatedAt, v.ID)
|
||||||
|
result.NextCursor = &next
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,320 @@
|
|||||||
|
"""Repeatable defensive checks against the local Lab7 Compose project."""
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import concurrent.futures
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / "tests"))
|
||||||
|
sys.path.insert(0, str(ROOT / "scripts"))
|
||||||
|
from bao import PRIVATE, compose, required, request, root_token, rotate_worker, unseal
|
||||||
|
from client import Client, check
|
||||||
|
from stack_action import inspect, stop_one
|
||||||
|
|
||||||
|
FIXTURE = ROOT / "tests/fixtures/sample.png"
|
||||||
|
|
||||||
|
|
||||||
|
def settings():
|
||||||
|
values = dict(line.split("=", 1) for line in (ROOT / ".env").read_text().splitlines()
|
||||||
|
if line and not line.lstrip().startswith("#") and "=" in line)
|
||||||
|
return values | os.environ
|
||||||
|
|
||||||
|
|
||||||
|
def api():
|
||||||
|
return Client(f"https://127.0.0.1:{int(settings().get('APP_PORT', 8443))}", str(PRIVATE / "ca.crt"), timeout=8)
|
||||||
|
|
||||||
|
|
||||||
|
def readiness(c):
|
||||||
|
try:
|
||||||
|
with c.opener.open(c.base + "/health/ready", timeout=3) as response:
|
||||||
|
return response.status
|
||||||
|
except urllib.error.HTTPError as response:
|
||||||
|
response.close()
|
||||||
|
return response.code
|
||||||
|
|
||||||
|
|
||||||
|
def wait_api(c, expected=200, timeout=65):
|
||||||
|
started = time.monotonic()
|
||||||
|
while time.monotonic() - started < timeout:
|
||||||
|
if readiness(c) == expected:
|
||||||
|
return time.monotonic() - started
|
||||||
|
time.sleep(0.4)
|
||||||
|
raise RuntimeError(f"API readiness did not reach HTTP {expected}")
|
||||||
|
|
||||||
|
|
||||||
|
def role_login(role, folder=None):
|
||||||
|
return required("auth/cert/login", method="POST", data={"name": role},
|
||||||
|
folder=folder or PRIVATE / "tls" / (role + "-client"))["auth"]
|
||||||
|
|
||||||
|
|
||||||
|
def bao_policy():
|
||||||
|
for role in ("api", "dispatcher", "worker", "jobs"):
|
||||||
|
folder = PRIVATE / "tls" / (role + "-client")
|
||||||
|
auth = role_login(role)
|
||||||
|
token = auth["client_token"]
|
||||||
|
check(auth["lease_duration"] == 45, "unexpected role lifetime")
|
||||||
|
own = required("lab/data/" + role, token=token, folder=folder)["data"]["data"]
|
||||||
|
check(not ({"root_token", "unseal_key", "s3_root_password"} & own.keys()), "operator secret in application KV")
|
||||||
|
for other in ("api", "dispatcher", "worker", "jobs"):
|
||||||
|
if other != role:
|
||||||
|
code, _ = request("lab/data/" + other, token=token, folder=folder)
|
||||||
|
check(code == 403, "cross-role KV read was not forbidden")
|
||||||
|
code, _ = request("sys/policies/acl/test", method="PUT", data={"policy": ""}, token=token, folder=folder)
|
||||||
|
check(code == 403, "service can write policy")
|
||||||
|
code, _ = request("auth/cert/login", method="POST", data={"name": role}, folder=PRIVATE / "tls/audit-client")
|
||||||
|
check(code in (400, 403), "same-CA audit identity obtained service token")
|
||||||
|
print("OpenBao: 4 scoped roles with 45s tokens; cross-role reads, policy writes and wrong same-CA identity denied")
|
||||||
|
|
||||||
|
|
||||||
|
def login_budget(c):
|
||||||
|
username = "audit_" + uuid.uuid4().hex[:12]
|
||||||
|
basic = base64.b64encode((username + ":synthetic-invalid-pass").encode()).decode()
|
||||||
|
replicas = set()
|
||||||
|
for _ in range(6):
|
||||||
|
resp = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + basic})
|
||||||
|
replicas.add(resp["headers"]["X-Instance-Id"])
|
||||||
|
blocked = c.call("POST", "/api/v1/auth/sessions", 429, headers={"Authorization": "Basic " + basic})
|
||||||
|
replicas.add(blocked["headers"]["X-Instance-Id"])
|
||||||
|
check(len(replicas) >= 2, "rate test did not exercise multiple replicas")
|
||||||
|
check(1 <= int(blocked["headers"]["Retry-After"]) <= 31, "missing or incorrect Retry-After")
|
||||||
|
print(f"Login limit: 6 attempts across {len(replicas)} replicas; attempt 7 received 429 with Retry-After")
|
||||||
|
|
||||||
|
|
||||||
|
def enforce_http(c):
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
attachment, _ = c.attachment(alice, chat)
|
||||||
|
path = "/api/v1/attachments/" + attachment["id"]
|
||||||
|
for suffix in ("", "/content"):
|
||||||
|
c.call("GET", path + suffix, 404, actor=eve, headers={"X-User-Id": alice["id"]})
|
||||||
|
private_chat = c.call("POST", "/api/v1/chats", 201, actor=eve,
|
||||||
|
body={"title": "ACL control", "member_ids": [eve["id"]]}, schema="Chat")["json"]
|
||||||
|
c.call("POST", f"/api/v1/chats/{private_chat['id']}/messages", 404, actor=eve,
|
||||||
|
body={"text": "", "attachment_ids": [attachment["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
|
||||||
|
c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", 413, actor=alice,
|
||||||
|
raw=b"", headers={"Content-Type": "image/png", "Content-Length": str(10 * 1024 * 1024 + 1),
|
||||||
|
"Expect": "100-continue"})
|
||||||
|
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=bob)
|
||||||
|
c.call("GET", "/api/v1/users/me", 401, actor=bob)
|
||||||
|
print("HTTP ACL: forged identity, outsider metadata/content and cross-chat attachment denied; size limit and logout passed")
|
||||||
|
return alice
|
||||||
|
|
||||||
|
|
||||||
|
def grafana():
|
||||||
|
password = (PRIVATE / "grafana_password").read_text().strip()
|
||||||
|
credential = base64.b64encode(("admin:" + password).encode()).decode()
|
||||||
|
ctx = ssl.create_default_context(cafile=str(PRIVATE / "ca.crt"))
|
||||||
|
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), urllib.request.HTTPSHandler(context=ctx))
|
||||||
|
port = int(settings().get("GRAFANA_PORT", 3443))
|
||||||
|
|
||||||
|
def call(path, *, authenticated=True):
|
||||||
|
headers = {"Authorization": "Basic " + credential} if authenticated else {}
|
||||||
|
req = urllib.request.Request(f"https://127.0.0.1:{port}" + path, headers=headers)
|
||||||
|
with opener.open(req, timeout=8) as response:
|
||||||
|
data = response.read(2 * 1024 * 1024)
|
||||||
|
return json.loads(data)
|
||||||
|
return call
|
||||||
|
|
||||||
|
|
||||||
|
def telemetry(c, actor):
|
||||||
|
get = grafana()
|
||||||
|
try:
|
||||||
|
get("/api/datasources", authenticated=False)
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
check(error.code == 401, "Grafana did not require authentication")
|
||||||
|
else:
|
||||||
|
raise RuntimeError("anonymous Grafana access succeeded")
|
||||||
|
event = c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||||
|
request_id = event["headers"]["X-Request-Id"]
|
||||||
|
prom = "/api/datasources/proxy/uid/lab-prom/api/v1/query?" + urllib.parse.urlencode({
|
||||||
|
"query": 'sum(messenger_http_requests_total{service_name="messenger-api"})'})
|
||||||
|
logs = "/api/datasources/proxy/uid/lab-loki/loki/api/v1/query_range?" + urllib.parse.urlencode({
|
||||||
|
"query": '{service_name="messenger-api"} | request_id="' + request_id + '"',
|
||||||
|
"start": str(time.time_ns() - 60_000_000_000), "limit": "10"})
|
||||||
|
for _ in range(26):
|
||||||
|
time.sleep(0.5)
|
||||||
|
metrics = get(prom)
|
||||||
|
logdata = get(logs)
|
||||||
|
rows = logdata["data"]["result"]
|
||||||
|
if metrics["data"]["result"] and rows:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
raise RuntimeError("API metrics and request id did not arrive at telemetry storage")
|
||||||
|
serial = json.dumps(rows)
|
||||||
|
match = re.search(r'"trace_id"\s*:\s*"([0-9a-f]{32})"', serial)
|
||||||
|
check(match is not None, "Loki request lost its trace id")
|
||||||
|
for _ in range(16):
|
||||||
|
try:
|
||||||
|
trace = get("/api/datasources/proxy/uid/lab-tempo/api/traces/" + match[1])
|
||||||
|
break
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
if error.code != 404:
|
||||||
|
raise
|
||||||
|
time.sleep(0.5)
|
||||||
|
else:
|
||||||
|
raise RuntimeError("Loki trace was not found in Tempo")
|
||||||
|
logs_all = compose("logs", "--no-color", "--tail", "75", "api", "worker", "openbao", "lb")
|
||||||
|
material = serial + json.dumps(trace) + logs_all
|
||||||
|
for value in (actor["token"], actor["registration"]["password"], root_token()):
|
||||||
|
check(value not in material, "credential leaked to a sampled signal")
|
||||||
|
print("Telemetry: Grafana auth, mTLS data sources, API metrics, Loki request id and corresponding Tempo trace verified")
|
||||||
|
print("Sampled traces, logs and service output contain no synthetic session/password or OpenBao root token")
|
||||||
|
|
||||||
|
|
||||||
|
def security():
|
||||||
|
c = api()
|
||||||
|
wait_api(c)
|
||||||
|
with socket.create_connection(("127.0.0.1", int(settings().get("APP_PORT", 8443))), timeout=5) as conn:
|
||||||
|
context = ssl.create_default_context(cafile=str(PRIVATE / "ca.crt"))
|
||||||
|
try:
|
||||||
|
with context.wrap_socket(conn, server_hostname="wrong.lab7.invalid"):
|
||||||
|
raise RuntimeError("ingress accepted wrong server name")
|
||||||
|
except ssl.SSLCertVerificationError as error:
|
||||||
|
check(error.verify_code == 62, "ingress failed for a reason other than hostname mismatch")
|
||||||
|
print("Ingress: verified CA works; mismatched external hostname rejected")
|
||||||
|
print(compose("--profile", "audit", "run", "--rm", "--no-deps", "-T", "audit").strip())
|
||||||
|
bao_policy()
|
||||||
|
login_budget(c)
|
||||||
|
actor = enforce_http(c)
|
||||||
|
telemetry(c, actor)
|
||||||
|
|
||||||
|
|
||||||
|
def track(count):
|
||||||
|
c = api()
|
||||||
|
wait_api(c)
|
||||||
|
alice, bob, _, chat = c.bootstrap()
|
||||||
|
sample, _ = c.attachment(alice, chat)
|
||||||
|
c.wait_ready(bob, sample)
|
||||||
|
compose("stop", "worker")
|
||||||
|
stopped = time.monotonic()
|
||||||
|
|
||||||
|
def accept(_):
|
||||||
|
start = time.monotonic()
|
||||||
|
att, content = c.attachment(alice, chat)
|
||||||
|
message = c.message(alice, chat, "", attachments=[att["id"]])["json"]
|
||||||
|
return att, content, message["id"], (time.monotonic() - start) * 1000
|
||||||
|
|
||||||
|
begin_acceptance = time.monotonic()
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
||||||
|
accepted = list(pool.map(accept, range(count)))
|
||||||
|
acceptance_seconds = time.monotonic() - begin_acceptance
|
||||||
|
for att, _, _, _ in accepted:
|
||||||
|
response = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")
|
||||||
|
check(response["json"]["status"] == "queued", "queued fixture advanced without worker")
|
||||||
|
before = compose("run", "--rm", "--no-deps", "-T", "worker", "security-probe", "worker",
|
||||||
|
data=json.dumps({"attachment": sample["id"], "staging": accepted[0][0]["id"]}))
|
||||||
|
print(before.strip())
|
||||||
|
rotation = time.monotonic()
|
||||||
|
rotate_worker()
|
||||||
|
activated = time.monotonic()
|
||||||
|
for att, content, _, _ in accepted:
|
||||||
|
ready = c.wait_ready(bob, att, wait_seconds=65)
|
||||||
|
check(ready["status"] == "ready", "job not restored")
|
||||||
|
original = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob)["bytes"]
|
||||||
|
check(hashlib.sha256(original).digest() == hashlib.sha256(content).digest(), "attachment bytes changed")
|
||||||
|
recovered = time.monotonic()
|
||||||
|
history = c.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=bob, schema="MessagePage")
|
||||||
|
by_id = {m["id"]: m["attachment_ids"] for m in history["json"]["items"]}
|
||||||
|
check(all(by_id.get(mid) == [att["id"]] for att, _, mid, _ in accepted), "message attachment link lost")
|
||||||
|
after = compose("exec", "-T", "worker", "/messenger", "security-probe", "worker",
|
||||||
|
data=json.dumps({"attachment": sample["id"]}))
|
||||||
|
check(all(line in before for line in after.splitlines()), "worker permissions changed after rotation")
|
||||||
|
times = sorted(item[3] for item in accepted)
|
||||||
|
summary = {"accepted": count, "ready": count, "lost": 0, "parallel_uploads": 2,
|
||||||
|
"accepted_per_second": round(count / acceptance_seconds, 2),
|
||||||
|
"accept_plus_message_ms": [round(item, 1) for item in times],
|
||||||
|
"p50_ms": round(times[math.ceil(count * 0.50) - 1], 1),
|
||||||
|
"p95_ms": round(times[math.ceil(count * 0.95) - 1], 1),
|
||||||
|
"p99_ms": round(times[math.ceil(count * 0.99) - 1], 1),
|
||||||
|
"rotation_s": round(activated - rotation, 2),
|
||||||
|
"activation_to_all_ready_s": round(recovered - activated, 2),
|
||||||
|
"worker_stop_to_all_ready_s": round(recovered - stopped, 2)}
|
||||||
|
print(json.dumps(summary, sort_keys=True))
|
||||||
|
|
||||||
|
|
||||||
|
def sealed():
|
||||||
|
c = api()
|
||||||
|
wait_api(c)
|
||||||
|
warm = time.monotonic()
|
||||||
|
required("sys/seal", token=root_token(), method="PUT", data={})
|
||||||
|
check(readiness(c) == 200, "existing cached credentials did not cover short seal")
|
||||||
|
try:
|
||||||
|
seconds = wait_api(c, 503, timeout=53)
|
||||||
|
print(f"Sealed OpenBao: last lease expired; verified HTTPS returned 503 after {seconds:.2f}s")
|
||||||
|
finally:
|
||||||
|
unseal()
|
||||||
|
recovery = wait_api(c, 200)
|
||||||
|
check(time.monotonic() - warm < 125, "seal recovery exceeded test deadline")
|
||||||
|
print(f"HTTPS readiness restored in {recovery:.2f}s after unseal")
|
||||||
|
|
||||||
|
|
||||||
|
def expiry():
|
||||||
|
env = os.environ.copy()
|
||||||
|
env["SESSION_TTL_SECONDS"] = "4"
|
||||||
|
args = ["docker", "compose", "up", "-d", "--no-build", "--no-deps", "--force-recreate", "api"]
|
||||||
|
c = api()
|
||||||
|
subprocess.run(args, env=env, cwd=ROOT, check=True, capture_output=True)
|
||||||
|
try:
|
||||||
|
wait_api(c)
|
||||||
|
actor = c.user("expiry")
|
||||||
|
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||||
|
time.sleep(4.2)
|
||||||
|
c.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||||
|
print("Session expiry: valid before configured TTL and rejected after expiry")
|
||||||
|
finally:
|
||||||
|
subprocess.run(args, cwd=ROOT, check=True, capture_output=True)
|
||||||
|
wait_api(c)
|
||||||
|
|
||||||
|
|
||||||
|
def failover_all():
|
||||||
|
c = api()
|
||||||
|
wait_api(c)
|
||||||
|
alice, bob, _, chat = c.bootstrap()
|
||||||
|
replicas = {node[0] for node in inspect(compose("ps", "-q", "api").split())}
|
||||||
|
check(len(replicas) == 2, "expected two active API containers")
|
||||||
|
confirmed = [c.message(alice, chat, "before sequential failover")["json"]]
|
||||||
|
for target in sorted(replicas):
|
||||||
|
try:
|
||||||
|
stop_one(target)
|
||||||
|
wait_api(c)
|
||||||
|
for step in range(5):
|
||||||
|
response = c.message(alice, chat, f"after stopping replica {len(confirmed)}-{step}")
|
||||||
|
check(response["headers"]["X-Instance-Id"] in replicas - {target}, "write bypassed survivor")
|
||||||
|
confirmed.append(response["json"])
|
||||||
|
history = c.call("GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=bob, schema="MessagePage")
|
||||||
|
check(history["json"]["items"] == confirmed, "history changed after replica loss")
|
||||||
|
finally:
|
||||||
|
compose("start", "api")
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
response = c.call("GET", "/health/ready", schema="Health")
|
||||||
|
if response["headers"]["X-Instance-Id"] == target:
|
||||||
|
break
|
||||||
|
time.sleep(0.2)
|
||||||
|
else:
|
||||||
|
raise RuntimeError("stopped replica did not rejoin the load balancer")
|
||||||
|
print("Sequential failover: both explicit API targets stopped, 10 writes on the respective survivor, history and session preserved")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("scenario", choices=("security", "track", "sealed", "expiry", "failover-all"))
|
||||||
|
parser.add_argument("--count", type=int, default=10)
|
||||||
|
args = parser.parse_args()
|
||||||
|
if not 1 <= args.count <= 30:
|
||||||
|
parser.error("--count must be between 1 and 30")
|
||||||
|
{"security": security, "track": lambda: track(args.count), "sealed": sealed, "expiry": expiry,
|
||||||
|
"failover-all": failover_all}[args.scenario]()
|
||||||
+291
@@ -0,0 +1,291 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"go.opentelemetry.io/otel"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
"go.opentelemetry.io/otel/codes"
|
||||||
|
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
||||||
|
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
||||||
|
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||||
|
otellog "go.opentelemetry.io/otel/log"
|
||||||
|
"go.opentelemetry.io/otel/metric"
|
||||||
|
"go.opentelemetry.io/otel/propagation"
|
||||||
|
sdklog "go.opentelemetry.io/otel/sdk/log"
|
||||||
|
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
||||||
|
"go.opentelemetry.io/otel/sdk/resource"
|
||||||
|
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
|
)
|
||||||
|
|
||||||
|
const telemetryScope = "mtusi/messenger"
|
||||||
|
|
||||||
|
var traceContext propagation.TraceContext
|
||||||
|
|
||||||
|
type telemetry struct {
|
||||||
|
logger otellog.Logger
|
||||||
|
requests metric.Int64Counter
|
||||||
|
httpTime metric.Float64Histogram
|
||||||
|
jobs metric.Int64Counter
|
||||||
|
jobTime metric.Float64Histogram
|
||||||
|
readyTime metric.Float64Histogram
|
||||||
|
workerBusy atomic.Int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func startTelemetry(role string, db *pgxpool.Pool, poolTrace *databaseTracer) (*telemetry, func(), error) {
|
||||||
|
if env("OTEL_SDK_DISABLED", "false") == "true" {
|
||||||
|
return nil, func() {}, nil
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
endpoint, err := url.Parse(env("OTEL_EXPORTER_OTLP_ENDPOINT", "https://otel-collector:4318"))
|
||||||
|
if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || endpoint.User != nil ||
|
||||||
|
endpoint.Path != "" || endpoint.RawQuery != "" || endpoint.Fragment != "" {
|
||||||
|
return nil, nil, errors.New("invalid OTLP TLS endpoint")
|
||||||
|
}
|
||||||
|
transport, err := labHTTPTransport(true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
client := &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||||
|
return http.ErrUseLastResponse
|
||||||
|
}}
|
||||||
|
host, err := os.Hostname()
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, errors.New("cannot identify telemetry instance")
|
||||||
|
}
|
||||||
|
res := resource.NewSchemaless(
|
||||||
|
attribute.String("service.name", "messenger-"+role),
|
||||||
|
attribute.String("service.version", "7.0.0"),
|
||||||
|
attribute.String("service.instance.id", host),
|
||||||
|
attribute.String("deployment.environment.name", env("APP_ENV", "lab")),
|
||||||
|
)
|
||||||
|
const exportTimeout = 2 * time.Second
|
||||||
|
tracer, err := otlptracehttp.New(ctx, otlptracehttp.WithTimeout(exportTimeout),
|
||||||
|
otlptracehttp.WithEndpointURL(endpoint.JoinPath("v1", "traces").String()), otlptracehttp.WithHTTPClient(client),
|
||||||
|
otlptracehttp.WithRetry(otlptracehttp.RetryConfig{Enabled: false}))
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, errors.New("invalid OTLP trace configuration")
|
||||||
|
}
|
||||||
|
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.AlwaysSample()),
|
||||||
|
sdktrace.WithBatcher(tracer, sdktrace.WithMaxQueueSize(1024), sdktrace.WithMaxExportBatchSize(128),
|
||||||
|
sdktrace.WithBatchTimeout(time.Second), sdktrace.WithExportTimeout(exportTimeout)))
|
||||||
|
var mp *sdkmetric.MeterProvider
|
||||||
|
var lp *sdklog.LoggerProvider
|
||||||
|
shutdown := func() {
|
||||||
|
end, cancel := context.WithTimeout(context.Background(), exportTimeout)
|
||||||
|
defer cancel()
|
||||||
|
if lp != nil {
|
||||||
|
_ = lp.Shutdown(end)
|
||||||
|
}
|
||||||
|
if mp != nil {
|
||||||
|
_ = mp.Shutdown(end)
|
||||||
|
}
|
||||||
|
_ = tp.Shutdown(end)
|
||||||
|
transport.CloseIdleConnections()
|
||||||
|
}
|
||||||
|
metrics, err := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTimeout(exportTimeout),
|
||||||
|
otlpmetrichttp.WithEndpointURL(endpoint.JoinPath("v1", "metrics").String()), otlpmetrichttp.WithHTTPClient(client),
|
||||||
|
otlpmetrichttp.WithRetry(otlpmetrichttp.RetryConfig{Enabled: false}))
|
||||||
|
if err != nil {
|
||||||
|
shutdown()
|
||||||
|
return nil, nil, errors.New("invalid OTLP metric configuration")
|
||||||
|
}
|
||||||
|
reader := sdkmetric.NewPeriodicReader(metrics, sdkmetric.WithInterval(2*time.Second),
|
||||||
|
sdkmetric.WithTimeout(exportTimeout))
|
||||||
|
mp = sdkmetric.NewMeterProvider(sdkmetric.WithResource(res), sdkmetric.WithReader(reader))
|
||||||
|
logs, err := otlploghttp.New(ctx, otlploghttp.WithTimeout(exportTimeout),
|
||||||
|
otlploghttp.WithEndpointURL(endpoint.JoinPath("v1", "logs").String()), otlploghttp.WithHTTPClient(client),
|
||||||
|
otlploghttp.WithRetry(otlploghttp.RetryConfig{Enabled: false}))
|
||||||
|
if err != nil {
|
||||||
|
shutdown()
|
||||||
|
return nil, nil, errors.New("invalid OTLP log configuration")
|
||||||
|
}
|
||||||
|
lp = sdklog.NewLoggerProvider(sdklog.WithResource(res),
|
||||||
|
sdklog.WithProcessor(sdklog.NewBatchProcessor(logs, sdklog.WithMaxQueueSize(1024),
|
||||||
|
sdklog.WithExportMaxBatchSize(128), sdklog.WithExportInterval(time.Second),
|
||||||
|
sdklog.WithExportBufferSize(1), sdklog.WithExportTimeout(exportTimeout))))
|
||||||
|
t, err := makeTelemetry(mp.Meter(telemetryScope))
|
||||||
|
if err == nil {
|
||||||
|
err = observeRuntime(mp.Meter(telemetryScope), role, db, poolTrace)
|
||||||
|
}
|
||||||
|
if err == nil && role == "worker" {
|
||||||
|
err = t.observeWorker(mp.Meter(telemetryScope))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
shutdown()
|
||||||
|
return nil, nil, fmt.Errorf("register telemetry instruments: %w", err)
|
||||||
|
}
|
||||||
|
t.logger = lp.Logger(telemetryScope)
|
||||||
|
otel.SetTracerProvider(tp)
|
||||||
|
// Exporter errors can contain the configured endpoint. Local diagnostics
|
||||||
|
// report the fixed event only, and never feed it back into the OTLP queue.
|
||||||
|
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(error) { slog.Warn("telemetry export failed") }))
|
||||||
|
return t, shutdown, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func makeTelemetry(m metric.Meter) (*telemetry, error) {
|
||||||
|
t := &telemetry{}
|
||||||
|
var err, errHTTP, errJobs, errJobTime, errReady error
|
||||||
|
t.requests, err = m.Int64Counter("messenger_http_requests")
|
||||||
|
t.httpTime, errHTTP = m.Float64Histogram("messenger_http_duration", metric.WithUnit("s"),
|
||||||
|
metric.WithExplicitBucketBoundaries(.002, .005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 30))
|
||||||
|
t.jobs, errJobs = m.Int64Counter("messenger_job_attempts")
|
||||||
|
t.jobTime, errJobTime = m.Float64Histogram("messenger_job_duration", metric.WithUnit("s"),
|
||||||
|
metric.WithExplicitBucketBoundaries(.01, .025, .05, .1, .25, .5, 1, 2, 3, 5, 10, 20, 30, 60, 120))
|
||||||
|
t.readyTime, errReady = m.Float64Histogram("messenger_attachment_time_to_ready", metric.WithUnit("s"),
|
||||||
|
metric.WithExplicitBucketBoundaries(.25, .5, 1, 2, 3, 5, 10, 20, 30, 60, 120, 300))
|
||||||
|
return t, errors.Join(err, errHTTP, errJobs, errJobTime, errReady)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *telemetry) event(ctx context.Context, event string, level otellog.Severity, fields ...attribute.KeyValue) {
|
||||||
|
if t == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var record otellog.Record
|
||||||
|
record.SetTimestamp(time.Now())
|
||||||
|
record.SetSeverity(level)
|
||||||
|
record.SetSeverityText(level.String())
|
||||||
|
record.SetBody(attribute.StringValue(event))
|
||||||
|
record.AddAttributes(attribute.String("event", event))
|
||||||
|
record.AddAttributes(fields...)
|
||||||
|
t.logger.Emit(ctx, record)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *telemetry) finishHTTP(ctx context.Context, route, method, requestID string, status int, start time.Time) {
|
||||||
|
if t == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
class := strconv.Itoa(status/100) + "xx"
|
||||||
|
dimensions := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route),
|
||||||
|
attribute.String("status_class", class))
|
||||||
|
duration := time.Since(start).Seconds()
|
||||||
|
t.requests.Add(ctx, 1, dimensions)
|
||||||
|
if class != "5xx" {
|
||||||
|
t.requests.Add(ctx, 0, metric.WithAttributes(attribute.String("method", method), attribute.String("route", route),
|
||||||
|
attribute.String("status_class", "5xx")))
|
||||||
|
}
|
||||||
|
t.httpTime.Record(ctx, duration, dimensions)
|
||||||
|
span := trace.SpanFromContext(ctx)
|
||||||
|
span.SetAttributes(attribute.Int("http.response.status_code", status))
|
||||||
|
severity := otellog.SeverityInfo
|
||||||
|
if status >= 500 {
|
||||||
|
span.SetStatus(codes.Error, "server_error")
|
||||||
|
severity = otellog.SeverityError
|
||||||
|
}
|
||||||
|
t.event(ctx, "http.request", severity, attribute.String("request_id", requestID),
|
||||||
|
attribute.String("route", route), attribute.String("method", method), attribute.Int("status", status),
|
||||||
|
attribute.Float64("duration_seconds", duration))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *telemetry) finishJob(ctx context.Context, j imageJob, outcome string, started time.Time) {
|
||||||
|
if t == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
duration := time.Since(started).Seconds()
|
||||||
|
dimensions := metric.WithAttributes(attribute.String("job_type", j.Type), attribute.String("outcome", outcome))
|
||||||
|
t.jobs.Add(ctx, 1, dimensions)
|
||||||
|
t.jobTime.Record(ctx, duration, dimensions)
|
||||||
|
severity := otellog.SeverityInfo
|
||||||
|
if outcome != "ready" {
|
||||||
|
trace.SpanFromContext(ctx).SetStatus(codes.Error, outcome)
|
||||||
|
severity = otellog.SeverityError
|
||||||
|
}
|
||||||
|
t.event(ctx, "image.attempt", severity, attribute.String("job_id", j.JobID),
|
||||||
|
attribute.Int("attempt", j.Attempt), attribute.String("outcome", outcome),
|
||||||
|
attribute.Float64("duration_seconds", duration))
|
||||||
|
}
|
||||||
|
|
||||||
|
func safeHTTPRoute(method, path string) (string, string) {
|
||||||
|
switch method {
|
||||||
|
case "GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS":
|
||||||
|
default:
|
||||||
|
method = "OTHER"
|
||||||
|
}
|
||||||
|
switch path {
|
||||||
|
case "/api/v1/users", "/api/v1/users/me", "/api/v1/auth/sessions",
|
||||||
|
"/api/v1/auth/sessions/current", "/api/v1/chats":
|
||||||
|
return method, path
|
||||||
|
}
|
||||||
|
parts := strings.SplitN(path, "/", 7)
|
||||||
|
if len(parts) >= 5 && parts[0] == "" && parts[1] == "api" && parts[2] == "v1" {
|
||||||
|
switch parts[3] {
|
||||||
|
case "chats":
|
||||||
|
if len(parts) == 5 {
|
||||||
|
return method, "/api/v1/chats/{chat_id}"
|
||||||
|
}
|
||||||
|
if len(parts) == 6 && (parts[5] == "messages" || parts[5] == "attachments") {
|
||||||
|
return method, "/api/v1/chats/{chat_id}/" + parts[5]
|
||||||
|
}
|
||||||
|
case "attachments":
|
||||||
|
if len(parts) == 5 {
|
||||||
|
return method, "/api/v1/attachments/{attachment_id}"
|
||||||
|
}
|
||||||
|
if len(parts) == 6 && parts[5] == "content" {
|
||||||
|
return method, "/api/v1/attachments/{attachment_id}/content"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return method, "unmatched"
|
||||||
|
}
|
||||||
|
|
||||||
|
func startSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
|
||||||
|
return otel.Tracer(telemetryScope).Start(ctx, name, opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func endSpan(span trace.Span, err error) {
|
||||||
|
if err != nil {
|
||||||
|
span.SetStatus(codes.Error, "operation_failed")
|
||||||
|
}
|
||||||
|
span.End()
|
||||||
|
}
|
||||||
|
|
||||||
|
func jobSpanAttributes(j imageJob) trace.SpanStartOption {
|
||||||
|
return trace.WithAttributes(attribute.String("messaging.system", "valkey"),
|
||||||
|
attribute.String("messaging.destination.name", imageStream),
|
||||||
|
attribute.String("messaging.message.id", j.JobID), attribute.Int("job.attempt", j.Attempt))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *telemetry) startJob(ctx context.Context, original propagation.MapCarrier, j imageJob, producer bool) (context.Context, trace.Span) {
|
||||||
|
if t != nil {
|
||||||
|
ctx = traceContext.Extract(ctx, original)
|
||||||
|
}
|
||||||
|
if producer {
|
||||||
|
return startSpan(ctx, "attachment-jobs publish", trace.WithSpanKind(trace.SpanKindProducer), jobSpanAttributes(j))
|
||||||
|
}
|
||||||
|
return startSpan(ctx, "attachment-jobs process", trace.WithSpanKind(trace.SpanKindConsumer), jobSpanAttributes(j))
|
||||||
|
}
|
||||||
|
|
||||||
|
// pgx receives full SQL and bind values. Export a fixed span name and status
|
||||||
|
// only, and skip calls outside a traced request or consumer.
|
||||||
|
func (*databaseTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, _ pgx.TraceQueryStartData) context.Context {
|
||||||
|
if !trace.SpanFromContext(ctx).IsRecording() {
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
child, span := startSpan(ctx, "postgresql query", trace.WithSpanKind(trace.SpanKindClient),
|
||||||
|
trace.WithAttributes(attribute.String("db.system.name", "postgresql")))
|
||||||
|
return context.WithValue(child, querySpanKey{}, span)
|
||||||
|
}
|
||||||
|
|
||||||
|
type querySpanKey struct{}
|
||||||
|
|
||||||
|
func (*databaseTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||||
|
if span, ok := ctx.Value(querySpanKey{}).(trace.Span); ok {
|
||||||
|
if errors.Is(data.Err, pgx.ErrNoRows) {
|
||||||
|
data.Err = nil
|
||||||
|
}
|
||||||
|
endSpan(span, data.Err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
"go.opentelemetry.io/otel/metric"
|
||||||
|
)
|
||||||
|
|
||||||
|
type databaseTracer struct {
|
||||||
|
acquiring atomic.Int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *databaseTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
|
||||||
|
d.acquiring.Add(1)
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *databaseTracer) TraceAcquireEnd(context.Context, *pgxpool.Pool, pgxpool.TraceAcquireEndData) {
|
||||||
|
d.acquiring.Add(-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func observeRuntime(m metric.Meter, role string, db *pgxpool.Pool, dbTrace *databaseTracer) error {
|
||||||
|
used, errUsed := m.Int64ObservableGauge("messenger_db_pool_used")
|
||||||
|
capacity, errMax := m.Int64ObservableGauge("messenger_db_pool_capacity")
|
||||||
|
waiting, errWaiting := m.Int64ObservableGauge("messenger_db_pool_acquiring")
|
||||||
|
waits, errWaits := m.Int64ObservableCounter("messenger_db_pool_waits")
|
||||||
|
cpu, errCPU := m.Float64ObservableCounter("messenger_container_cpu", metric.WithUnit("s"))
|
||||||
|
memory, errMemory := m.Int64ObservableGauge("messenger_container_memory", metric.WithUnit("By"))
|
||||||
|
depth, errDepth := m.Int64ObservableGauge("messenger_queue_depth")
|
||||||
|
age, errAge := m.Float64ObservableGauge("messenger_queue_oldest_age", metric.WithUnit("s"))
|
||||||
|
slo, errSLO := m.Int64ObservableCounter("messenger_attachment_slo_jobs")
|
||||||
|
if err := errors.Join(errUsed, errMax, errWaiting, errWaits, errCPU, errMemory, errDepth, errAge, errSLO); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
instruments := []metric.Observable{used, capacity, waiting, waits, cpu, memory}
|
||||||
|
if role == "dispatcher" {
|
||||||
|
instruments = append(instruments, depth, age, slo)
|
||||||
|
}
|
||||||
|
_, err := m.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
||||||
|
stat := db.Stat()
|
||||||
|
o.ObserveInt64(used, int64(stat.AcquiredConns()))
|
||||||
|
o.ObserveInt64(capacity, int64(stat.MaxConns()))
|
||||||
|
o.ObserveInt64(waiting, dbTrace.acquiring.Load())
|
||||||
|
o.ObserveInt64(waits, stat.EmptyAcquireCount())
|
||||||
|
if data, err := os.ReadFile("/sys/fs/cgroup/cpu.stat"); err == nil {
|
||||||
|
for _, line := range strings.Split(string(data), "\n") {
|
||||||
|
if micros, found := strings.CutPrefix(line, "usage_usec "); found {
|
||||||
|
if value, err := strconv.ParseFloat(micros, 64); err == nil {
|
||||||
|
o.ObserveFloat64(cpu, value/1e6)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if data, err := os.ReadFile("/sys/fs/cgroup/memory.current"); err == nil {
|
||||||
|
if value, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64); err == nil {
|
||||||
|
o.ObserveInt64(memory, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if role != "dispatcher" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
sample, cancel := context.WithTimeout(ctx, 700*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
var pending, good, matured int64
|
||||||
|
var oldest float64
|
||||||
|
// Measure SQL backlog including jobs waiting for a retry or for XADD.
|
||||||
|
// Count each first publication exactly once, at its SLO deadline,
|
||||||
|
// even if the worker is down or its final state is failed.
|
||||||
|
err := db.QueryRow(sample, `
|
||||||
|
WITH sample AS (SELECT statement_timestamp() AS now)
|
||||||
|
SELECT count(*) FILTER (WHERE state='queued'),
|
||||||
|
coalesce(extract(epoch FROM (sample.now - min(created_at) FILTER (WHERE state='queued'))), 0)::float8,
|
||||||
|
count(*) FILTER (WHERE version=1 AND created_at <= sample.now - interval '5 seconds'),
|
||||||
|
count(*) FILTER (WHERE version=1 AND created_at <= sample.now - interval '5 seconds'
|
||||||
|
AND ready_at <= created_at + interval '5 seconds')
|
||||||
|
FROM sample LEFT JOIN image_jobs ON true GROUP BY sample.now`).Scan(&pending, &oldest, &matured, &good)
|
||||||
|
if err == nil {
|
||||||
|
queue := metric.WithAttributes(attribute.String("queue", imageStream))
|
||||||
|
o.ObserveInt64(depth, pending, queue)
|
||||||
|
o.ObserveFloat64(age, oldest, queue)
|
||||||
|
o.ObserveInt64(slo, good, metric.WithAttributes(attribute.String("outcome", "good")))
|
||||||
|
o.ObserveInt64(slo, matured-good, metric.WithAttributes(attribute.String("outcome", "missed")))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}, instruments...)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *telemetry) observeWorker(m metric.Meter) error {
|
||||||
|
used, errUsed := m.Int64ObservableGauge("messenger_worker_busy")
|
||||||
|
capacity, errCapacity := m.Int64ObservableGauge("messenger_worker_capacity")
|
||||||
|
if err := errors.Join(errUsed, errCapacity); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := m.RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||||
|
o.ObserveInt64(used, t.workerBusy.Load())
|
||||||
|
o.ObserveInt64(capacity, 1)
|
||||||
|
return nil
|
||||||
|
}, used, capacity)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
)
|
||||||
|
|
||||||
|
const tlsDir = "/run/lab-tls"
|
||||||
|
const revocations = "/run/lab-revocation/serials"
|
||||||
|
|
||||||
|
func trustRoots() (*x509.CertPool, error) {
|
||||||
|
pem, err := os.ReadFile(tlsDir + "/ca.crt")
|
||||||
|
roots := x509.NewCertPool()
|
||||||
|
if err != nil || !roots.AppendCertsFromPEM(pem) {
|
||||||
|
return nil, errors.New("cannot load TLS CA")
|
||||||
|
}
|
||||||
|
return roots, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func leaf(dir string) (tls.Certificate, error) {
|
||||||
|
pair, err := tls.LoadX509KeyPair(dir+"/tls.crt", dir+"/tls.key")
|
||||||
|
if err != nil {
|
||||||
|
return pair, errors.New("cannot load TLS leaf")
|
||||||
|
}
|
||||||
|
return pair, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func clientTLS(mutual bool) (*tls.Config, error) {
|
||||||
|
roots, err := trustRoots()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cfg := &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}
|
||||||
|
if mutual {
|
||||||
|
pair, err := leaf(tlsDir)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cfg.Certificates = []tls.Certificate{pair}
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func trustedPeer(cert *x509.Certificate) error {
|
||||||
|
data, err := os.ReadFile(revocations)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("revocation data unavailable")
|
||||||
|
}
|
||||||
|
for _, serial := range strings.Fields(string(data)) {
|
||||||
|
if strings.EqualFold(cert.SerialNumber.Text(16), serial) {
|
||||||
|
return errors.New("client leaf revoked")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !time.Now().Before(cert.NotAfter) {
|
||||||
|
return errors.New("client leaf expired")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func clientIdentity(cert *x509.Certificate) string {
|
||||||
|
if len(cert.DNSNames) != 1 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return cert.DNSNames[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func serverTLS(allowed []string) (*tls.Config, error) {
|
||||||
|
pair, err := leaf(env("LAB_SERVER_TLS_DIR", tlsDir))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cfg := &tls.Config{MinVersion: tls.VersionTLS12, Certificates: []tls.Certificate{pair}, SessionTicketsDisabled: true}
|
||||||
|
if len(allowed) == 0 {
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
cfg.ClientCAs, err = trustRoots()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cfg.ClientAuth = tls.RequireAndVerifyClientCert
|
||||||
|
cfg.VerifyConnection = func(state tls.ConnectionState) error {
|
||||||
|
cert := state.PeerCertificates[0]
|
||||||
|
if !slices.Contains(allowed, clientIdentity(cert)) {
|
||||||
|
return errors.New("client identity denied")
|
||||||
|
}
|
||||||
|
return trustedPeer(cert)
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func labHTTPTransport(mutual bool) (*http.Transport, error) {
|
||||||
|
cfg, err := clientTLS(mutual)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &http.Transport{
|
||||||
|
TLSClientConfig: cfg, DialContext: (&net.Dialer{Timeout: 2 * time.Second}).DialContext,
|
||||||
|
MaxIdleConns: 16, MaxIdleConnsPerHost: 8, MaxConnsPerHost: 16, IdleConnTimeout: 30 * time.Second,
|
||||||
|
ResponseHeaderTimeout: 5 * time.Second, TLSHandshakeTimeout: 3 * time.Second,
|
||||||
|
DisableCompression: true,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func redisTLS(rawURL string, mutual bool) (*redis.Options, error) {
|
||||||
|
opts, err := redis.ParseURL(rawURL)
|
||||||
|
if err != nil || opts.TLSConfig == nil || opts.Username == "" || opts.Password == "" {
|
||||||
|
return nil, errors.New("invalid TLS Valkey configuration")
|
||||||
|
}
|
||||||
|
host, _, err := net.SplitHostPort(opts.Addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("invalid Valkey address")
|
||||||
|
}
|
||||||
|
opts.TLSConfig, err = clientTLS(mutual)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
opts.TLSConfig.ServerName = host
|
||||||
|
opts.Protocol = 2
|
||||||
|
opts.DisableIdentity = true
|
||||||
|
return opts, nil
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user