Secure messenger with TLS identities, scoped OpenBao secrets and worker compromise experiments
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
name: implemented-secure-messenger
|
||||
on: [push, pull_request]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
integration:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- run: python3 -m pip install -r requirements-dev.txt
|
||||
- run: make check validate
|
||||
- run: make up
|
||||
- run: make test test-security
|
||||
- run: python3 student-tests/security.py
|
||||
- run: make test-race
|
||||
- run: make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
- run: make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
- if: always()
|
||||
run: docker compose down -v --remove-orphans
|
||||
@@ -30,3 +30,6 @@ coverage/
|
||||
.vscode/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
# Locally generated CA certificate and operator/test state
|
||||
certs/ca.crt
|
||||
infra/tls/revoked.json
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
# ЛР7: понятный разбор для защиты
|
||||
|
||||
## Что я делал — ответ на первый вопрос
|
||||
|
||||
«Я взял свой работающий мессенджер из шестой лабы и защитил соединения и доступы между его частями. Пользователь обращается по HTTPS. Балансировщик и каждая копия API проверяют сертификаты друг друга; API принимает только сертификат роли балансировщика. База, файловое хранилище, очередь и система наблюдения тоже доступны по защищённым соединениям.
|
||||
|
||||
Я разделил права сервисов. Обработчик фотографий не может читать пароли, пользовательские сессии и сообщения или менять владельца файла. Нужные пароли сервисы получают из OpenBao — отдельного хранилища секретов — по своему сертификату и ограниченной политике. Ключи оператора в приложение не передаются.
|
||||
|
||||
Для исследования я смоделировал утечку доступа обработчика: проверил разрешённые и запрещённые действия, остановил старый процесс, отозвал его доступ, заменил пароль БД и сертификат. Затем запустил чистый обработчик из того же образа и проверил завершение уже принятых задач и совпадение исходных файлов».
|
||||
|
||||
## Схема системы
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
U[Пользователь] -->|HTTPS| L[HAProxy: балансировщик]
|
||||
L -->|mTLS, только роль LB| A[Две API]
|
||||
A -->|TLS + отдельная роль| P[(PostgreSQL)]
|
||||
A -->|mTLS + права на файлы| S[(S3 / MinIO)]
|
||||
P --> D[Отправитель заданий]
|
||||
D -->|mTLS + право добавить| B[(Очередь Valkey)]
|
||||
B -->|mTLS + право обработать| W[Обработчик фотографий]
|
||||
W --> S
|
||||
W --> P
|
||||
A -->|Свой сертификат, своя политика| O[OpenBao]
|
||||
W --> O
|
||||
A -->|mTLS| C[Сборщик наблюдений]
|
||||
W -->|mTLS| C
|
||||
C --> T[Prometheus / Loki / Tempo]
|
||||
T --> G[Grafana]
|
||||
```
|
||||
|
||||
Для части программ TLS выполняет небольшой шлюз рядом с ними. Шлюз и программа используют одно сетевое пространство, а незашифрованный участок ограничен127.0.0.1 внутри этой границы. Из соседнего контейнера этот локальный порт недоступен. Это проверяется соединением из другого контейнера, а не только чтением конфигурации.
|
||||
|
||||
## Термины без лишней сложности
|
||||
|
||||
| Термин | Что означает здесь |
|
||||
|---|---|
|
||||
| TLS / HTTPS | Защищённое соединение. Клиент проверяет сертификат сервера и имя адресата, данные шифруются |
|
||||
| mTLS | Обе стороны предъявляют сертификаты: сервер также проверяет клиента |
|
||||
| CA, центр сертификации | Доверенный издатель сертификатов; его закрытый ключ находится у оператора |
|
||||
| SAN | Поле сертификата с разрешёнными именами. Проверяем точное имя нужного сервиса |
|
||||
| EKU | Разрешённое применение ключа: клиентское или серверное. Ключ worker не получает право представлять HTTPS ingress |
|
||||
| Identity | Кем представляется соединяющийся сервис, например worker.client.lab |
|
||||
| Политика / ACL | Список разрешённых действий. Узнать, кто подключился, недостаточно — нужно разрешить действие |
|
||||
| Credential / secret | Пароль, ключ или другое подтверждение доступа, которое нельзя публиковать |
|
||||
| Leaf certificate | Обычный сертификат конкретного сервиса, подписанный CA |
|
||||
| TTL | Срок действия. Например, сервисный токен OpenBao имеет срок60 секунд |
|
||||
| Rotation / ротация | Замена пароля или сертификата на новый с прекращением использования старого |
|
||||
| Revoke / отзыв | Запрет ранее выданного доступа |
|
||||
| OpenBao | Сервис, который хранит секреты и выдаёт их после проверки identity и политики |
|
||||
| Sealed / закрытый Bao | OpenBao не открыл своё зашифрованное хранилище и не выдаёт секреты |
|
||||
| Unseal / открытие Bao | Действие оператора с частями ключа, позволяющее Bao работать с хранилищем |
|
||||
| tmpfs | Временные файлы в памяти контейнера; туда попадают рабочие секреты |
|
||||
| Argon2id | Функция для хранения паролей, специально требующая времени и памяти при проверке |
|
||||
| Rehash | Пересчёт сохранённого хеша с более сильными параметрами после успешного входа |
|
||||
|
||||
## Четыре вопроса из README с ответами
|
||||
|
||||
**1. Какая часть mTLS проверяет шифрование, какая идентичность и где разрешение на действие?**
|
||||
|
||||
При установлении TLS стороны договариваются о ключах, затем данные защищаются шифрованием и контролем целостности. Проверка сертификата устанавливает identity: кто подключился, доверяем ли издателю, не истёк ли срок и соответствует ли имя ожидаемому. В mTLS сертификат проверяет и сервер, и клиент.
|
||||
|
||||
Разрешение действия задаётся отдельно. API разрешает роль LB; очередь дополнительно проверяет свои имя пользователя/пароль и команды; PostgreSQL — права SQL-роли; S3 — права пользователя на нужную область файлов; OpenBao — политику своего пути. Пользователь всё равно должен предъявить Bearer-сессию и состоять в чате. mTLS между сервисами не делает пользователя участником любого чата.
|
||||
|
||||
**2. Почему доверенный CA ещё не означает, что любой его клиент может быть LB?**
|
||||
|
||||
CA подписывает сертификаты разных ролей: обработчика, сборщика наблюдений, балансировщика. Подпись доказывает, что сертификат выдал наш центр, но роль может быть неподходящей. Поэтому API проверяет точный DNS SANlb.client.lab. Сертификат worker или outsider от того же CA отклоняется.
|
||||
|
||||
Сертификаты также ограничены по назначению. Worker получает клиентский ключ без серверного назначения и без имён localhost/LB. Иначе чрезмерно широкий сертификат мог бы дать ему ненужную возможность представляться сервером. Отрицательные проверки выполняются для каждой API-копии, брокера и Collector.
|
||||
|
||||
**3. Где хранится первый секрет для доступа к OpenBao и кто имеет право unseal?**
|
||||
|
||||
Первоначальное доверие создаёт оператор: выпускает короткоживущий сертификат сервиса и передаёт ему только его закрытый ключ и публичный CA. Приложение доказывает владение своим ключом при аутентификации в Bao и получает ограниченный токен. В образе нет общего вечного токена «для получения всех секретов».
|
||||
|
||||
Ключ CA, root token и части ключа для открытия Bao находятся в закрытом каталоге оператора на host. Они не монтируются в API/worker и в сам Bao. Для открытия нужны2 части из3. В учебном стенде всеми частями владеет один оператор; независимые держатели/HSM не реализованы. После рестарта Bao оператор явно выполняет make unseal. Приложение самостоятельно открыть Bao не может.
|
||||
|
||||
**4. Что происходит при истечении credentials, остановке OpenBao и рестарте API?**
|
||||
|
||||
Истёкший сертификат отклоняется при проверке TLS. Истёкшая/отозванная пользовательская сессия даёт401. Сервис повторяет вход в Bao и чтение секретов каждые5 секунд. После последнего успешного чтения он допускает использование конфигурации не дольше60 секунд, затем останавливает рабочий процесс. Проверка TLS не отключается.
|
||||
|
||||
Если API перезапустить при закрытом Bao, он не сможет заново получить секреты и не начнёт обслуживать бизнес-запросы. Уже работавшая другая API может работать до окончания ограниченного срока. После открытия Bao сервисы снова получают конфигурацию; прежние пользовательские сессии и данные остаются в PG/S3.
|
||||
|
||||
Важно различать токен Bao и выданный пароль БД: истечение токена само по себе не меняет статический пароль. Мы отдельно заменяем пароль SQL-роли и завершаем её старые соединения. В эксперименте старый пароль проверяется с новым допустимым сертификатом, поэтому отказ нельзя объяснить только отзывом старого сертификата.
|
||||
|
||||
## Что проверялось на практике
|
||||
|
||||
1. HTTPS проходит с правильным CA; чужой CA/неверное имя сервера отклоняются проверкой сертификата.
|
||||
2. Каждая API принимает сертификат LB и отвергает отсутствие сертификата, другой CA и запрещённую роль нашего CA.
|
||||
3. Обработчик не может читать users/sessions/messages, менять владельца/контрольную сумму исходника, публиковать новые задания или очистить очередь.
|
||||
4. В S3 обработчик может читать исходники и записывать окончательные изображения, но не писать в staging/private, не удалять final и не администрировать buckets.
|
||||
5. У OpenBao каждая служба читает свой путь; чужой secret и изменение политики дают403. Worker не получает cursor/cache secrets API.
|
||||
6. Чужой пользователь не читает и не прикрепляет чужое вложение. Поддельный X-User-Id не меняет владельца Bearer-сессии.
|
||||
7. Вход ограничен общим счётчиком двух API; есть429/Retry-After. Старый Argon2 hash повышается при успешном входе.
|
||||
8. Отзыв worker identity/пароля, закрытие Bao, восстановление и сохранность файлов проверяются отдельными воспроизводимыми сценариями.
|
||||
9. Старые возможности сохраняются: upload202, очередь, настоящие варианты изображений, идемпотентность сообщений, лог/trace через весь путь, Grafana с реальными TLS-запросами к трём хранилищам.
|
||||
|
||||
## Как объяснить исследование на пятёрку
|
||||
|
||||
Гипотеза: если обработчику выдать отдельные минимальные права, утечка его доступа не раскроет пароли/сессии/сообщения. После отзыва и замены доступа чистый обработчик сможет завершить ранее принятую работу.
|
||||
|
||||
Исследование сравнивает явно названные запросы. В операторском baseline с общими расширенными credentials чтение password table и администрирование S3 разрешены. С настоящими worker credentials — запрещены. Разрешённая область тоже показана: pipeline SQL, чтение staging, запись final prefix, обработка очереди. Затем старый процесс изолируется, доступ отзывается, пароль и сертификат меняются, новый процесс запускается без пересборки образа.
|
||||
|
||||
Числа и ошибки смотри в REPORT.md и evidence/worker-compromise*.json. Не утверждай нулевой простой: первый опыт сохранил98 успешных сообщений и2 ошибки во время восстановления. Не утверждай, что worker вообще безвреден: он всё ещё может читать изображения всех чатов, портить разрешённые final objects и данные обработки. Это проверенное ограничение ущерба в конкретной модели.
|
||||
|
||||
## Команды демонстрации
|
||||
|
||||
```sh
|
||||
make up
|
||||
make test
|
||||
make test-security
|
||||
python3 student-tests/security.py
|
||||
python3 student-tests/compromise.py
|
||||
python3 student-tests/sealed.py
|
||||
python3 student-tests/hardening.py
|
||||
python3 student-tests/telemetry.py
|
||||
```
|
||||
|
||||
Запускай сценарии по одному. Для сохранённых результатов достаточно открыть evidence; повторное исследование создаёт новые synthetic data и меняет рабочие credentials. После демонстрации отказа API восстанови обе копии командой docker compose up -d --no-deps --wait api.
|
||||
|
||||
Операторские возможности предыдущей лабы доступны отдельно:
|
||||
|
||||
```sh
|
||||
docker compose --profile verify run --rm operator cleanup
|
||||
# По умолчанию dry-run; --apply только для явно проверенной очистки.
|
||||
docker compose --profile verify run --rm operator replay ATTACHMENT_UUID
|
||||
docker compose --profile verify run --rm operator reprocess ATTACHMENT_UUID
|
||||
```
|
||||
|
||||
## Дополнительные вопросы, которые может задать преподаватель
|
||||
|
||||
**Почему нельзя хранить пароль как SHA256?** Он слишком быстро проверяется перебором. Argon2id расходует память и CPU. SHA256 сессионного случайного256-bit токена решает другую задачу: пароль человек выбирает предсказуемо, токен создаётся генератором случайных чисел.
|
||||
|
||||
**Что даёт соль?** Одинаковые пароли получают разные хеши, заранее подготовленные таблицы не подходят сразу ко всем пользователям. Соль не секрет, хранится рядом с параметрами и результатом.
|
||||
|
||||
**Может ли TLS заменить проверку доступа к чату?** Нет. TLS защищает канал и identity сервиса; membership и действительность пользовательской сессии проверяет API через PG.
|
||||
|
||||
**Зачем отзыв сертификата проверять на новом подключении?** Уже открытое соединение могло пройти проверку раньше. У нас HTTP повторно проверяет serial на запросах, stream соединение ограничено30s, SQL connections при смене пароля завершаются отдельно. Начатый HTTP request ограничен35s.
|
||||
|
||||
**Почему нельзя просто заменить секрет у работающего взломанного процесса?** Злоумышленник может прочитать новую конфигурацию. Поэтому сначала останавливается старый worker, затем выдаётся новый доступ и запускается чистый процесс.
|
||||
|
||||
**Что доказывает scanner0findings?** Что конкретный scanner по конкретной базе не обнаружил известные уязвимости Go-зависимостей в данном коде. Он не доказывает отсутствие ошибок в собственном коде или всех контейнерах. В SCAN_TRIAGE.md разобраны обновления и ограничения.
|
||||
|
||||
**Есть ли отказоустойчивость при потере ноутбука/БД/S3/Bao?** Нет. Один host и одиночные хранилища остаются точками отказа. Шифрование и разные права не создают резервную копию или второй узел.
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
FROM golang:1.27.4-alpine3.24 AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
ARG GOPROXY=https://proxy.golang.org,direct
|
||||
RUN --mount=type=cache,target=/go/pkg/mod GODEBUG=http2client=0 GOPROXY="$GOPROXY" go mod download
|
||||
COPY cmd/ ./cmd/
|
||||
COPY internal/ ./internal/
|
||||
RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server
|
||||
|
||||
FROM build AS tests
|
||||
RUN apk add --no-cache gcc musl-dev libwebp-tools
|
||||
RUN --mount=type=cache,target=/go/pkg/mod mkdir -p /opt/gomod && cp -a /go/pkg/mod/. /opt/gomod/
|
||||
ENV CGO_ENABLED=1 GOMODCACHE=/opt/gomod
|
||||
CMD ["go", "test", "-race", "-count=1", "-v", "./..."]
|
||||
|
||||
FROM alpine:3.24.4
|
||||
RUN apk add --no-cache libwebp-tools
|
||||
RUN addgroup -g 10001 app && adduser -D -u 10001 -G app app
|
||||
COPY --from=build /out/messenger /usr/local/bin/messenger
|
||||
USER 10001:10001
|
||||
ENV APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=5s --timeout=4s --start-period=3s --retries=3 CMD ["/usr/local/bin/messenger", "healthcheck"]
|
||||
STOPSIGNAL SIGTERM
|
||||
ENTRYPOINT ["/usr/local/bin/messenger"]
|
||||
@@ -0,0 +1,11 @@
|
||||
ЛР 7 — БВТ 2303 — Крайкин — на 5
|
||||
|
||||
Автор: Крайкин Глеб Алексеевич, БВТ2303. Цель: 5, трек1 — компрометация worker.
|
||||
|
||||
Работающий мессенджер из собственной ЛР6 переведён на HTTPS с mTLS LB→каждая API; DB/S3/broker/cache/OTel/Grafana/OpenBao связи защищены проверяемым TLS и scoped identities/permissions. Native listeners за gateways доступны только в том же loopback namespace. Добавлены non-dev OpenBao2.7.3/Raft, certificate auth, короткие service tokens, ограниченное поведение при sealed/expiry, ротация SQL secret и leaf, серийный отзыв сертификатов. Worker не получает API cursor/cache secrets, не читает users/sessions/messages и не имеет административных прав S3/broker.
|
||||
|
||||
Реальное исследование показывает baseline с расширенными правами и последствия утечки настоящего worker credential, разрешённые/запрещённые SQL/S3/queue/Bao действия, quarantine/revoke/rotate/replacement и сохранность всех принятых оригиналов без rebuild. Публичные HTTPS smoke/TLS, PG/race/rehash, ACL/logout/expiry, общий rate limit/parallel login budget, последовательный отказ обеих API, полный persistence и настоящая telemetry через Grafana проверены; результаты и ограничения в REPORT.md/evidence. Запуск: make up; make check; make test; make test-security. Секреты создаются локально вне Git/images.
|
||||
|
||||
Модель угроз и фактическая матрица: security/THREAT_MODEL.md, security/TRUST_MATRIX.md. Реальный dependency scan найденные библиотеки исправлены, повторный govulncheck0findings; применимость/границы описаны в SCAN_TRIAGE.md. Контракты API и публичные tests сохранены; предусмотренная заданием trust matrix заполнена. DEFENSE.md содержит понятный рассказ, схемы, словарь и все четыре вопроса README.
|
||||
|
||||
Один host и shared stores остаются SPOF, volume не backup. Компрометация CA/host вне модели; worker всё ещё имеет разрешённые права на все images/pipeline. Cache авторизации до60s, bounded revocation30/35s; статические KV credentials меняются явно, TTL токена не отзывает SQL password. Remote CI не объявляется выполненным. Использован Codex, первичные источники указаны в отчёте.
|
||||
@@ -1,6 +1,6 @@
|
||||
PYTHON ?= python3
|
||||
BASE_URL ?= https://localhost:8443
|
||||
CA_FILE ?=
|
||||
CA_FILE ?= $(CURDIR)/certs/ca.crt
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
@@ -31,3 +31,14 @@ test-failover:
|
||||
|
||||
test-security:
|
||||
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
bootstrap:
|
||||
$(PYTHON) scripts/bootstrap.py
|
||||
up:
|
||||
$(PYTHON) scripts/up.py
|
||||
unseal:
|
||||
$(PYTHON) scripts/bao_operator.py unseal
|
||||
down:
|
||||
docker compose down
|
||||
test-race:
|
||||
docker compose --profile verify run --build --rm tests
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Запуск ЛР7
|
||||
|
||||
Нужны Docker/Compose, Python3.9+, openssl. Go на host не нужен. Всё запускается из этого репозитория.
|
||||
|
||||
```sh
|
||||
make up
|
||||
make check
|
||||
make test
|
||||
make test-security
|
||||
python3 student-tests/security.py
|
||||
make test-race
|
||||
```
|
||||
|
||||
`make up` от имени локального оператора создаёт CA/leaf и credentials, собирает приложение, поднимает все сервисы, выполняет миграции и init/unseal/configuration Bao. Секреты/ключи не печатаются и не включаются в Git/images; существующие credentials сохраняются. На повторном запуске истекающие leaf обновляются, процессы пересоздаются с сохранением volumes.
|
||||
|
||||
- REST: https://localhost:8443, trust CA — certs/ca.crt.
|
||||
- Grafana: https://localhost:3007; anonymous выключен, operator admin password в ignored secrets/grafana_password.
|
||||
- OpenBao: https://localhost:8207, только оператор; root token и shares в ignored secrets/operator/init.json.
|
||||
- API/PG/S3/broker/cache/telemetry native ports не опубликованы.
|
||||
|
||||
Браузеру локальный CA автоматически не устанавливается. CLI tests уже используют правильный CA; не отключайте проверку сертификата. `make down` сохраняет volumes. После отдельного рестарта OpenBao он sealed: явный `make unseal` выполняет оператор, приложения shares не получают.
|
||||
|
||||
```sh
|
||||
python3 student-tests/compromise.py # исследование пятёрки, свои synthetic data
|
||||
python3 student-tests/sealed.py # ограниченный отказ Bao и expired leaf
|
||||
python3 scripts/rotate.py rotate worker
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
docker compose up -d --no-deps --wait api # вернуть API после failover
|
||||
```
|
||||
|
||||
Все fault/rotation сценарии выполнять последовательно. Они меняют только этот учебный Compose-проект. Не удаляйте рабочие volumes для проверки persistence. Перечень угроз, доверительных границ и пределы отзыва — security/THREAT_MODEL.md и TRUST_MATRIX.md. Рассказ и вопросы — DEFENSE.md; измерения — REPORT.md/evidence.
|
||||
|
||||
Для сохранённых операторских replay/reprocess/cleanup: `docker compose --profile verify run --rm operator cleanup` (dry-run), `operator replay UUID`, `operator reprocess UUID`. Эти одноразовые процессы имеют операторский доступ; runtime worker его не получает.
|
||||
@@ -1,37 +1,94 @@
|
||||
# Отчёт — лабораторная 7
|
||||
# ЛР7: безопасность работающего мессенджера
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
Крайкин Глеб Алексеевич, БВТ2303. Цель: **5, трек1 — компрометация worker и ограничение последствий**. Эксперименты2 декабря2026, synthetic data, один учебный Docker Desktop host. Оценку выставляет преподаватель после проверки и объяснения.
|
||||
|
||||
## Запуск из чистого clone
|
||||
## Происхождение и запуск
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Skeleton `20afc2c790d3e72f6b7666376c9834c1ced1a405`. Перенесена собственная ЛР6 `d18fe254e983918b58949bbd70ebfaf64085d44a`: две API, общие PG sessions, идемпотентные messages, private S3, durable staging/outbox, Streams, отдельные worker/dispatcher/cleanup, version fencing/retry, OTel/Grafana. Репозиторий самостоятельный. README/COURSE/OpenAPI/публичные tests сохранены; предусмотренный заданием template trust matrix заполнен ссылками на фактическую матрицу, без изменения бизнес-семантики.
|
||||
|
||||
## Архитектура и решения
|
||||
```sh
|
||||
make up
|
||||
make check
|
||||
make validate PYTHON=/путь/к/venv/bin/python # requirements-dev.txt
|
||||
make test
|
||||
make test-security
|
||||
python3 student-tests/security.py
|
||||
make test-race
|
||||
```
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Docker/Compose, Python3.9+, openssl; Go на host не нужен. CA/credentials создаёт оператор, значения скрыты. REST https://localhost:8443; CA certs/ca.crt. Grafana https://localhost:3007, anonymous выключен; OpenBao operator endpoint https://localhost:8207. Все host ports loopback. [QUICKSTART](QUICKSTART.md) — команды отказов/ротации; [DEFENSE](DEFENSE.md) — простой рассказ, схемы, вопросы README; [модель угроз](security/THREAT_MODEL.md), [полная матрица](security/TRUST_MATRIX.md).
|
||||
|
||||
## Доказательства критериев
|
||||
## Реализация границ доверия
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
Внешний HTTPS на HAProxy, native mTLS LB→все API. Go TLS server проверяет CA/expiry и exact DNS SANlb.client.lab, client сертификат другого сервиса того же CA отвергается. Public X-Instance-Id — случайный UUID alias жизни API process, hostname/IP не раскрывается. Local health127.0.0.1:8081 обслуживает только live/ready.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
PostgreSQL native TLS/verify-full, hostnossl reject, SCRAM и отдельные ограниченные роли; schema owner существует только в отдельной migration/operator задаче. Общие sessions/ACL проверяются PG, optional profile cache не определяет авторизацию. Worker не имеет SELECT users/sessions/messages, не меняет ownership исходников и не может создавать schema/roles.
|
||||
|
||||
## Эксперименты и отказы
|
||||
Для остальных stores gateway и native backend находятся в одном network namespace. Native listener привязан только127.0.0.1, сетевой listener gateway — TLS/mTLS с exact SAN и разрешением операции. Безопасность включает закрытый локальный hop, а не обещание шифровать память внутри скомпрометированной boundary. Broker: mTLSdispatcher/worker + отдельные Valkey ACL, producer/consumer commands и один stream key. Collector: разные identities API/worker/dispatcher/housekeeping, POST только ingestion paths. Collector→Loki/Tempo и Grafana/Prometheus→stores используют mTLS и разные permissions. Grafana имеет только query rights. Metrics scrape/health/admin включены в матрицу.
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
App/worker/gateways UID10001, read_only, drop ALL capabilities, no-new-privileges; tmpfs для временных файлов/секретов, CPU/RAM limits. Stateful volumes writable, исключения и bootstrap caps названы в матрице. Verify-only compiler container имеет отдельный executable tmpfs и повышенный memory budget; это не runtime API. Docker socket/host network/privileged контейнеров нет.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
## OpenBao и lifecycle
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
OpenBao2.7.3, non-dev, persistent **Raft с одним voter**, декларативный persistent file audit с HMAC значений. Один voter не даёт HA. Оператор создаёт CA365d и leaves24h, выполняет init3shares/threshold2, unseal и policies. CA key, root token/shares находятся только в ignored host operator directory0700/0600, не в Bao/API/worker mounts. Bootstrap доверяет локальному оператору и host; внешнего HSM, distributed share custody и защиты от root host не заявлено.
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Service certificate auth pinned leaf + SAN даёт scoped token60s, только own KVv2 path. Supervisor каждые5s повторно аутентифицируется, читает secrets и отзывает использованный token. Runtime values существуют в памяти/tmpfs, не в image или Compose Env. Последнее успешное чтение даёт ограниченное authorization cache60s; при изменении credentials child перезапускается, при невозможности refresh после deadline останавливается. После обычного рестарта API не нужны operator keys, при sealed Bao новый API не стартует с зашитым запасным секретом.
|
||||
|
||||
KV SQL/S3 credentials статические; TTL токена **не отзывает сам пароль БД**. SQL secret меняется явно: ALTER PASSWORD и terminate старых sessions. Leaf/client reload — на новых handshakes; serial denylist проверяется при handshake и каждом HTTP request, raw stream connection имеет30s absolute deadline, active HTTP request≤35s. Operator certificate auth/token отзываются отдельно. Это bounded revocation, не мгновенный отзыв уже переданных данных. `scripts/rotate.py` меняет SQL password+leaf без rebuild. При инциденте worker сначала карантинируется и заменяется чистым процессом.
|
||||
|
||||
## Пароли и ограничение входа
|
||||
|
||||
Argon2id:64MiB,3passes,2lanes, случайный salt16bytes, hash32bytes. PHC хранит algorithm/version/params/salt/hash. Проверка constant-time; parser старых допустимых параметров ограничен сверху перед выделением памяти. Успешный login повышает старый hash до текущих параметров; интеграционный HTTP/PG test проверяет действительное изменение строки, неверные credentials не создают session. Worker не получает API cursor/cache secrets; dispatcher получает только SQL/broker credentials. Leaf SAN/EKU разделены: worker — только clientAuth, без serverAuth/localhost. Bearer имеет256bit энтропии, в PG только SHA256 digest32bytes, logout и expiry проверяются при каждом запросе.
|
||||
|
||||
Общий для реплик PG admission: максимум12 auth attempts/username/fixed minute,120 global; registration также проходит этот budget. Максимум2 одновременных KDF/API, превышение429 с Retry-After. Измеренный invalid-login KDF/HTTP p50≈73.265ms, max182.701ms в последнем прогоне. Две API показаны в одном rate test; после лимита429. KDF рабочая память ограничена примерно128MiB/API плюс остальная память процесса. Fixed windows допускают двойной burst на границе; глобальный лимит допускает отказ в обслуживании auth при исчерпании бюджета и не является полноценной защитой от distributed DoS.
|
||||
|
||||
## Исследование на5
|
||||
|
||||
**Гипотеза:** разделение SQL/S3/broker/Bao identities ограничит ущерб при утечке worker credentials до изображения/pipeline, а quarantine+revoke+rotation позволит завершить уже принятые задачи без потери оригиналов.
|
||||
|
||||
Повторяемая методика: `python3 student-tests/compromise.py`. Из работающего worker читаются только его runtime snapshot и leaf, копия сохраняется в ignored operator/test files. Запросы выполняются с этой identity, без CA/root/host/Docker прав. «До разделения» — явно операторский изолированный probe с API SQL credential и S3 root credential, не выдаваемыми реальному worker. Этот baseline показывает риск общего credential; не изображает компрометацию host.
|
||||
|
||||
1. Baseline может читать password table и выполнять S3 bucket administration.
|
||||
2. Реальный worker читает pipeline и staging своего принятого файла, подключается к своей очереди. Passwords/sessions/messages, owner mutation/schema DROP, staging write/private prefix/bucket admin, XADD/FLUSHALL/other stream и чужой Bao secret запрещены.
|
||||
3. Worker остановлен,8 uploads приняты через202, идёт background text traffic. Отзываются старый serial, cert auth и выданный token; SQL password заменён с завершением соединений; выдаётся новый leaf и пересоздаётся worker из того же image.
|
||||
4. Старый cert не подключается к broker/S3; старый SQL password проверяется с **новым доверенным cert**, чтобы доказать именно отзыв secret. Новый worker подключается, все8 accepted files становятся ready и побайтно совпадают.
|
||||
|
||||
**Финальный опыт:** все8 ready за3.823s от начала remediation; background messages80success/0errors; image IDs до/после совпали. Реально выполнены также разрешённый UPDATE execution status и PUT marker в final prefix; изменение checksum/owner и удаление final запрещены. Первый опыт4.101s/98success/2errors сохранён отдельно в `worker-compromise-first.json`; причины двух ошибок в нём не классифицированы, нулевой простой не обещается. Финальные raw allow/deny — `evidence/worker-compromise.json`. Оставшийся ущерб: worker имеет право читать images всех чатов, писать final variants и execution metadata; per-job scoped tokens нет, полнота защиты от malicious worker не заявляется.
|
||||
|
||||
## Проверка expiry/sealed
|
||||
|
||||
`student-tests/sealed.py`: корректный worker SAN с подписанным, но истёкшим leaf отвергнут broker. Bao sealed, одна API перезапущена. Последняя работающая API прекратила business traffic через60.698s, после operator unseal прежняя session/file восстановились за4.324s. Cache60s + polling5s/экспорт/read timeouts объясняют границу; это не бесконечный fallback и не мгновенное выключение по seal. `evidence/sealed-expiry.json` сохраняет actual HTTP timeline.
|
||||
|
||||
## Dependency scan и версии
|
||||
|
||||
Go1.27.4 / Alpine3.24.4. OTel trace/metric/sdk1.47.0, sdk/log1.47.0, HTTP log exporter0.23.0, otelslog0.21.0; pgx5.9.2, x/crypto0.59.0, x/image0.45.0, compress1.20.2; точные indirect pins в go.mod/go.sum. Остальная инфраструктура закреплена compose tags: PG17.6, Valkey8.1.3, HAProxy3.2.6, MinIO RELEASE.2025-09-07T16-13-09Z, Collector0.128.0, Prometheus3.4.1, Loki3.5.1, Tempo2.8.0, Grafana12.0.2.
|
||||
|
||||
Реальный govulncheck1.10.0, Go Vulnerability DB modified2026-11-24: после обновления Go, но до обновления библиотек —423 findings/24 called advisories; после обновления библиотек —0 findings. Raw streams сжаты в `dependency-scan*.json.gz`, читаемое сравнение — `dependency-scan-summary.json`. Команды и разбор применимости — [SCAN_TRIAGE.md](security/SCAN_TRIAGE.md). Это dependency/call-graph scan приложения; OS packages и сторонние контейнеры этим результатом не объявлены свободными от CVE.
|
||||
|
||||
## Границы доказательств и источники
|
||||
|
||||
Single host, одиночные PG/S3/broker/LB/Bao/telemetry stores — SPOF; named volume не backup. Модель не включает root host/CA, автоматический rollover CA, per-job credentials и защиту от произвольного code execution в API. Учебный TLS gateway — собственный небольшой компонент с отрицательными проверками, не независимый security audit. Закрытый loopback hop честно указан. Remote CI не объявляется выполненным.
|
||||
|
||||
Использованы собственные ЛР4–6, контракты преподавателя, Codex для реализации/проверок/объяснений. Первичные источники: [OpenBao cert auth](https://openbao.org/docs/auth/cert/), [declarative audit](https://openbao.org/docs/configuration/audit/), [Raft](https://openbao.org/docs/configuration/storage/raft/), [OWASP password storage](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html), [Go Vulnerability Database](https://vuln.go.dev/), [Go TLS](https://pkg.go.dev/crypto/tls). Автор должен уметь объяснить и изменить решение на защите.
|
||||
|
||||
|
||||
## Сводка проверок и нагрузка
|
||||
|
||||
| Проверка | Фактический результат / evidence |
|
||||
|---|---|
|
||||
| Неизменённые make check / полный OpenAPI | PASS, check.txt / openapi.txt |
|
||||
| Public HTTPS smoke / TLS trust | PASS, smoke.txt / public-tls.txt |
|
||||
| Обе API, broker, Collector, все backend links | Positive и no cert/alien CA/wrong same-CA identity; CA/hostname errors, trust-matrix.json |
|
||||
| Bao policies и минимальные secrets | Own read, чужой path/policy403, wrong cert role denied, revoked token403; openbao-policy.json |
|
||||
| Attachment ACL / logout / expiry / forged header | PASS, application-security.json |
|
||||
| Real PG + race + legacy Argon2 rehash | PASS, race.txt:101 concurrent/idempotent effects, Unicode, actual HTTP rehash, JPEG/PNG EXIF/alpha, child failure classification |
|
||||
| Parallel login budget | 8 clients /24 attempts:14 real KDF401,10 capacity429 с Retry-After; cgroup lifetime peaks301240320/300556288bytes, cap768MiB/API; auth-budget.json |
|
||||
| Каждый API отдельно |148success/1error, recovery1.118s;143success/2errors, recovery0.306s; confirmed messages preserved, operations.json |
|
||||
| Public failover |110success/1failed attempt, recovery1.149s; старый token/data сохранены, failover.txt |
|
||||
| Полный persistence | PASS через HTTPS, старые token/messages/file, restart всех store/gateway/backend; persistence.txt, окончательное actual StartedAt дополнительно проверяется clean clone |
|
||||
| Контейнеры и bypass | Реальные UID/read-only/caps/ports/mounts, запрет native ports извне, worker rootfs/other keys denied; hardening.json |
|
||||
| Реальная наблюдаемость | API→dispatcher→worker→S3/DB trace+Loki correlation; метрики; actual Grafana proxy queries ко всем3 stores, telemetry.json |
|
||||
|
||||
Нагрузка с включёнными TLS/mTLS и telemetry:4 closed-loop clients, без warmup,15.010s;2386success/0errors,158.960 successful RPS, success p50/p95/p99=8.173/129.663/196.474ms. Размеры данных до/после и реальные Docker CPU/RAM observations — load-resources.json. Это растущий набор данных на общей VM, не максимальная capacity и не сравнительное исследование цены TLS. Percentiles включают только успехи, ошибки считаются отдельно, есть coordinated omission.
|
||||
|
||||
Измерения login memory — lifetime peak контейнера после пробы, а не изолированная трассировка allocation этого опыта. Fresh Git clone/new CA/new stores проверяются отдельным student-tests/clean_clone.py; финальный commit и process evidence фиксируются после прогона. Удалённый CI не заявляется выполненным.
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"log/slog"
|
||||
"mtusi/messenger/internal/database"
|
||||
"mtusi/messenger/internal/messenger"
|
||||
"mtusi/messenger/internal/security"
|
||||
"mtusi/messenger/internal/telemetry"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func env(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
if errors.Is(err, messenger.ErrInvalidImage) {
|
||||
os.Exit(65)
|
||||
}
|
||||
slog.Error("server failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func run() error {
|
||||
if len(os.Args) == 2 && os.Args[1] == "probe" {
|
||||
return security.Probe()
|
||||
}
|
||||
if len(os.Args) > 1 && (os.Args[1] == "gateway" || os.Args[1] == "supervise") {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if os.Args[1] == "gateway" {
|
||||
if len(os.Args) != 3 {
|
||||
return fmt.Errorf("gateway config required")
|
||||
}
|
||||
return security.Gateway(ctx, os.Args[2])
|
||||
}
|
||||
if len(os.Args) < 3 {
|
||||
return fmt.Errorf("supervised command required")
|
||||
}
|
||||
return security.Supervise(ctx, os.Args[2:])
|
||||
}
|
||||
|
||||
if (len(os.Args) == 4 || len(os.Args) == 5) && os.Args[1] == "transform" {
|
||||
version := 1
|
||||
if len(os.Args) == 5 {
|
||||
v, e := strconv.Atoi(os.Args[4])
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
version = v
|
||||
}
|
||||
return messenger.Transform(os.Args[2], os.Args[3], version)
|
||||
}
|
||||
host := env("APP_HOST", "0.0.0.0")
|
||||
port := env("APP_PORT", "8080")
|
||||
p, err := strconv.Atoi(port)
|
||||
if err != nil || p < 1 || p > 65535 {
|
||||
return fmt.Errorf("invalid APP_PORT")
|
||||
}
|
||||
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
|
||||
c := http.Client{Timeout: time.Second}
|
||||
r, e := c.Get("http://127.0.0.1:8081/health/ready")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer r.Body.Close()
|
||||
if r.StatusCode != 200 {
|
||||
return fmt.Errorf("not ready: %d", r.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
service := "messenger-api"
|
||||
if len(os.Args) > 1 {
|
||||
service = "messenger-" + os.Args[1]
|
||||
}
|
||||
if len(os.Args) == 1 || os.Args[1] != "migrate" {
|
||||
var shutdown func()
|
||||
var e error
|
||||
log, shutdown, e = telemetry.Init(context.Background(), service)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer shutdown()
|
||||
}
|
||||
slog.SetDefault(log)
|
||||
ttl, err := strconv.Atoi(env("SESSION_TTL_SECONDS", "3600"))
|
||||
if err != nil || ttl < 1 || ttl > 86400 {
|
||||
return fmt.Errorf("SESSION_TTL_SECONDS must be 1..86400")
|
||||
}
|
||||
databaseURL, err := secret("DATABASE_URL_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
startup, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
pool, err := database.Open(startup, databaseURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
if len(os.Args) == 2 && os.Args[1] == "migrate" {
|
||||
return database.Migrate(startup, pool)
|
||||
}
|
||||
command := "api"
|
||||
if len(os.Args) > 1 {
|
||||
command = os.Args[1]
|
||||
}
|
||||
var objects *messenger.ObjectStore
|
||||
if command != "dispatcher" {
|
||||
storeAccess, err := secret("S3_ACCESS_KEY_ID_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
storeSecret, err := secret("S3_SECRET_ACCESS_KEY_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
objects, err = messenger.NewObjectStore(env("S3_ENDPOINT", "https://s3:9000"), env("S3_BUCKET", "messenger-attachments"), storeAccess, storeSecret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(os.Args) > 1 {
|
||||
command := os.Args[1]
|
||||
if command == "worker" || command == "dispatcher" || command == "replay" || command == "reprocess" || command == "cleanup" || command == "housekeeping" {
|
||||
var broker *redis.Client
|
||||
if command == "worker" || command == "dispatcher" {
|
||||
brokerURL, e := secret("BROKER_URL_FILE")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
opts, e := redis.ParseURL(brokerURL)
|
||||
if e != nil {
|
||||
return fmt.Errorf("invalid broker configuration")
|
||||
}
|
||||
opts.TLSConfig, e = security.ClientTLS()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
opts.MaxRetries = -1
|
||||
opts.DialTimeout = time.Second
|
||||
opts.ReadTimeout = 2 * time.Second
|
||||
opts.WriteTimeout = 2 * time.Second
|
||||
broker = redis.NewClient(opts)
|
||||
defer broker.Close()
|
||||
}
|
||||
telemetry.Observe(pool, command == "dispatcher")
|
||||
pipeline := messenger.NewPipeline(pool, broker, objects, log)
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
switch command {
|
||||
case "worker":
|
||||
n, e := strconv.Atoi(env("WORKER_CONCURRENCY", "1"))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
return pipeline.RunWorker(ctx, n)
|
||||
case "dispatcher":
|
||||
return pipeline.RunDispatcher(ctx)
|
||||
case "housekeeping":
|
||||
return pipeline.RunHousekeeping(ctx)
|
||||
case "cleanup":
|
||||
return pipeline.Cleanup(ctx, len(os.Args) == 3 && os.Args[2] == "--apply")
|
||||
case "replay", "reprocess":
|
||||
if len(os.Args) != 3 {
|
||||
return fmt.Errorf("expected attachment UUID")
|
||||
}
|
||||
return pipeline.Replay(ctx, os.Args[2], command == "reprocess")
|
||||
}
|
||||
}
|
||||
}
|
||||
cacheURL, err := secret("CACHE_URL_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cursorKey, err := secret("CURSOR_KEY_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := base64.RawURLEncoding.DecodeString(cursorKey)
|
||||
if err != nil || len(key) != 32 {
|
||||
return fmt.Errorf("invalid cursor key")
|
||||
}
|
||||
opts, err := redis.ParseURL(cacheURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid cache configuration")
|
||||
}
|
||||
opts.TLSConfig, err = security.ClientTLS()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts.DialTimeout = 60 * time.Millisecond
|
||||
opts.ReadTimeout = 60 * time.Millisecond
|
||||
opts.WriteTimeout = 60 * time.Millisecond
|
||||
opts.PoolTimeout = 60 * time.Millisecond
|
||||
opts.ContextTimeoutEnabled = true
|
||||
opts.MaxRetries = -1
|
||||
opts.PoolSize = 10
|
||||
cache := redis.NewClient(opts)
|
||||
defer cache.Close()
|
||||
telemetry.Observe(pool, false)
|
||||
api := messenger.New(pool, cache, key, ttl, log)
|
||||
api.SetObjectStore(objects)
|
||||
srv := &http.Server{Addr: net.JoinHostPort(host, port), Handler: api, ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 35 * time.Second, WriteTimeout: 35 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
// Only loopback, only health routes; it cannot bypass mTLS for business API.
|
||||
health := &http.Server{Addr: "127.0.0.1:8081", ReadHeaderTimeout: time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/health/live" && r.URL.Path != "/health/ready" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
api.ServeHTTP(w, r)
|
||||
})}
|
||||
go health.ListenAndServe()
|
||||
defer health.Close()
|
||||
srv.IdleTimeout = 2 * time.Second
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
log.Info("listening", "address", srv.Addr, "session_store", "postgres", "profile_cache", "valkey", "environment", env("APP_ENV", "lab"))
|
||||
tc, e := security.ServerTLS([]string{"lb"})
|
||||
if e != nil {
|
||||
done <- e
|
||||
return
|
||||
}
|
||||
srv.Handler = security.AuthorizeHTTP(tc, api)
|
||||
listener, e := tls.Listen("tcp", srv.Addr, tc)
|
||||
if e != nil {
|
||||
done <- e
|
||||
return
|
||||
}
|
||||
done <- srv.Serve(listener)
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
}
|
||||
start := time.Now()
|
||||
api.Stop()
|
||||
log.Info("shutdown started")
|
||||
shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdown); err != nil {
|
||||
_ = srv.Close()
|
||||
return err
|
||||
}
|
||||
err = <-done
|
||||
if !errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
log.Info("shutdown completed", "duration_ms", time.Since(start).Milliseconds())
|
||||
return nil
|
||||
}
|
||||
|
||||
func secret(name string) (string, error) {
|
||||
if value, ok := security.RuntimeSecret(name); ok {
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("missing runtime secret %s", name)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
path := os.Getenv(name)
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("missing %s", name)
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot read %s", name)
|
||||
}
|
||||
return strings.TrimSpace(string(raw)), nil
|
||||
}
|
||||
+1075
File diff suppressed because it is too large
Load Diff
+15
-13
@@ -1,21 +1,21 @@
|
||||
# Матрица доверия — заполнить в решении lab7
|
||||
# Матрица доверия — решение ЛР7
|
||||
|
||||
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
||||
|
||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
||||
| --- | --- | --- | --- |
|
||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | Реальные endpoints/CA/SAN/ACL/TTL и команды: [заполненная матрица](../security/TRUST_MATRIX.md); evidence/trust-matrix.json, student-tests/security.py |
|
||||
|
||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
||||
|
||||
@@ -35,3 +35,5 @@
|
||||
OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии.
|
||||
|
||||
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
|
||||
|
||||
Матрица решения детально заполнена в [security/TRUST_MATRIX.md](../security/TRUST_MATRIX.md), модель угроз — [THREAT_MODEL.md](../security/THREAT_MODEL.md). API→broker: N/A, API использует transactional outbox; межузловая replication не добавлялась. Остальные строки покрыты TLS/mTLS и отрицательными проверками указанного сценария.
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"attachment_acl": true,
|
||||
"forged_identity_denied": true,
|
||||
"cross_chat_attachment_denied": true,
|
||||
"expired_session_denied": true,
|
||||
"logout_denied": true,
|
||||
"hashes_only": true,
|
||||
"token_hash_bytes": true
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
{
|
||||
"scope": "shared username bucket on two real API replicas, unknown username KDF, sequential invalid attempts",
|
||||
"attempts": [
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.15739225,
|
||||
"instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.18270066599999998,
|
||||
"instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.11214866600000001,
|
||||
"instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.070015041,
|
||||
"instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.11456191599999999,
|
||||
"instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.07591387500000002,
|
||||
"instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.06304100000000001,
|
||||
"instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.06627162500000006,
|
||||
"instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.09612395900000004,
|
||||
"instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.07061700000000004,
|
||||
"instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.06350758299999981,
|
||||
"instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.07031729200000014,
|
||||
"instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5",
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.006560708999999942,
|
||||
"instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f",
|
||||
"retry_after": "60"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.007485750000000069,
|
||||
"instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5",
|
||||
"retry_after": "60"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.006046124999999902,
|
||||
"instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f",
|
||||
"retry_after": "60"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.006384166999999996,
|
||||
"instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5",
|
||||
"retry_after": "60"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.004841917000000029,
|
||||
"instance": "ed5b693e-20a0-4f8a-9cae-48f1950da10f",
|
||||
"retry_after": "60"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.004661250000000061,
|
||||
"instance": "065ee0d5-9f97-465d-8908-238a3e5e86f5",
|
||||
"retry_after": "60"
|
||||
}
|
||||
],
|
||||
"kdf_parameters": {
|
||||
"memory_kib": 65536,
|
||||
"passes": 3,
|
||||
"lanes": 2,
|
||||
"slots_per_api": 2
|
||||
},
|
||||
"successful_kdf_observed_ms": {
|
||||
"p50": 73.26543750000003,
|
||||
"max": 182.70066599999998
|
||||
},
|
||||
"limits": {
|
||||
"per_username_per_fixed_minute": 12,
|
||||
"global_auth_per_fixed_minute": 120,
|
||||
"boundary_max_two_adjacent_windows": 24
|
||||
},
|
||||
"bound": "2*64MiB KDF working memory per API plus image/process memory; excess concurrent KDF admission returns429",
|
||||
"parallel_login_probe": {
|
||||
"concurrency": 8,
|
||||
"attempts": 24,
|
||||
"responses": [
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.234659,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.181604,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.676529,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.18093,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.553548,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.565564,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.605484,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.231737,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.185875,
|
||||
"retry_after": "1"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.084691,
|
||||
"retry_after": "1"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.106126,
|
||||
"retry_after": "1"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.13174,
|
||||
"retry_after": "1"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.099201,
|
||||
"retry_after": "1"
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.40589,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.193023,
|
||||
"retry_after": "1"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.197215,
|
||||
"retry_after": "1"
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.316612,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.39436,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.39396,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.26043,
|
||||
"retry_after": "1"
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.195508,
|
||||
"retry_after": "1"
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.34017,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 401,
|
||||
"seconds": 0.296132,
|
||||
"retry_after": null
|
||||
},
|
||||
{
|
||||
"status": 429,
|
||||
"seconds": 0.240738,
|
||||
"retry_after": "1"
|
||||
}
|
||||
],
|
||||
"api_container_lifetime_memory_peak_bytes_after_probe": [
|
||||
301240320,
|
||||
300556288
|
||||
],
|
||||
"memory_scope": "cgroup lifetime peak, not an isolated allocation trace; API cap768MiB each"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
PASS: shared two-replica rate limit, real concurrent KDF admission429/Retry-After and measured memory budget
|
||||
@@ -0,0 +1,152 @@
|
||||
Compose can now delegate builds to bake for better performance.
|
||||
To do so, set COMPOSE_BAKE=true.
|
||||
#0 building with "desktop-linux" instance using docker driver
|
||||
|
||||
#1 [tests internal] load build definition from Dockerfile
|
||||
#1 transferring dockerfile: 1.11kB done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [api internal] load build definition from Dockerfile
|
||||
#2 transferring dockerfile: 1.11kB done
|
||||
#2 DONE 0.0s
|
||||
|
||||
#3 [api internal] load metadata for docker.io/library/alpine:3.24.4
|
||||
#3 DONE 0.0s
|
||||
|
||||
#4 [tests internal] load metadata for docker.io/library/golang:1.27.4-alpine3.24
|
||||
#4 DONE 0.0s
|
||||
|
||||
#5 [tests internal] load .dockerignore
|
||||
#5 transferring context: 196B done
|
||||
#5 DONE 0.0s
|
||||
|
||||
#6 [api internal] load .dockerignore
|
||||
#6 transferring context: 196B done
|
||||
#6 DONE 0.0s
|
||||
|
||||
#7 [api stage-2 1/4] FROM docker.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
|
||||
#7 resolve docker.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf 0.0s done
|
||||
#7 DONE 0.0s
|
||||
|
||||
#8 [tests build 1/7] FROM docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280
|
||||
#8 resolve docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 0.0s done
|
||||
#8 DONE 0.0s
|
||||
|
||||
#9 [api internal] load build context
|
||||
#9 transferring context: 37.30kB done
|
||||
#9 DONE 0.0s
|
||||
|
||||
#10 [tests internal] load build context
|
||||
#10 transferring context: 37.30kB done
|
||||
#10 DONE 0.0s
|
||||
|
||||
#11 [api build 3/7] COPY go.mod go.sum ./
|
||||
#11 CACHED
|
||||
|
||||
#12 [api build 2/7] WORKDIR /src
|
||||
#12 CACHED
|
||||
|
||||
#13 [api build 4/7] RUN --mount=type=cache,target=/go/pkg/mod GODEBUG=http2client=0 GOPROXY="https://proxy.golang.org,direct" go mod download
|
||||
#13 CACHED
|
||||
|
||||
#14 [tests build 5/7] COPY cmd/ ./cmd/
|
||||
#14 CACHED
|
||||
|
||||
#15 [tests build 6/7] COPY internal/ ./internal/
|
||||
#15 DONE 0.0s
|
||||
|
||||
#16 [api build 7/7] RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server
|
||||
#16 DONE 10.4s
|
||||
|
||||
#17 [tests build 7/7] RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server
|
||||
#17 CACHED
|
||||
|
||||
#12 [tests build 2/7] WORKDIR /src
|
||||
#12 CACHED
|
||||
|
||||
#18 [tests build 4/7] RUN --mount=type=cache,target=/go/pkg/mod GODEBUG=http2client=0 GOPROXY="https://proxy.golang.org,direct" go mod download
|
||||
#18 CACHED
|
||||
|
||||
#19 [tests build 6/7] COPY internal/ ./internal/
|
||||
#19 CACHED
|
||||
|
||||
#20 [tests build 5/7] COPY cmd/ ./cmd/
|
||||
#20 CACHED
|
||||
|
||||
#21 [tests build 3/7] COPY go.mod go.sum ./
|
||||
#21 CACHED
|
||||
|
||||
#22 [api stage-2 2/4] RUN apk add --no-cache libwebp-tools
|
||||
#22 CACHED
|
||||
|
||||
#23 [api stage-2 3/4] RUN addgroup -g 10001 app && adduser -D -u 10001 -G app app
|
||||
#23 CACHED
|
||||
|
||||
#24 [api stage-2 4/4] COPY --from=build /out/messenger /usr/local/bin/messenger
|
||||
#24 DONE 0.0s
|
||||
|
||||
#25 [api] exporting to image
|
||||
#25 exporting layers
|
||||
#25 exporting layers 0.5s done
|
||||
#25 exporting manifest sha256:4d8a2b0fbbb6c5c88d1dcd6979f46f2f35fa2ccdbe72650944f8a5b42ac3f4b9
|
||||
#25 exporting manifest sha256:4d8a2b0fbbb6c5c88d1dcd6979f46f2f35fa2ccdbe72650944f8a5b42ac3f4b9 done
|
||||
#25 exporting config sha256:4e044b8aad682a9b15c59ebd0eded9e519c5f22ba5b72c020d2f00cb73f6c739 done
|
||||
#25 exporting attestation manifest sha256:069d2d05259e5e1c6f7e52bbd6419527412d160cb3bd4601a631c6f4f93fa6fe done
|
||||
#25 exporting manifest list sha256:0cc4658eae5fb71ea4a44ffb5584d5d1c650eda5887702e992c65552c8f789db done
|
||||
#25 naming to docker.io/library/mtusi-messenger:lab7 done
|
||||
#25 unpacking to docker.io/library/mtusi-messenger:lab7 0.1s done
|
||||
#25 DONE 0.7s
|
||||
|
||||
#26 [tests tests 1/2] RUN apk add --no-cache gcc musl-dev libwebp-tools
|
||||
#26 ...
|
||||
|
||||
#27 [api] resolving provenance for metadata file
|
||||
#27 DONE 0.0s
|
||||
|
||||
#26 [tests tests 1/2] RUN apk add --no-cache gcc musl-dev libwebp-tools
|
||||
#26 1.175 ( 1/22) Installing libgcc (15.2.0-r5)
|
||||
#26 1.266 ( 2/22) Installing jansson (2.15.0-r0)
|
||||
#26 1.356 ( 3/22) Installing libstdc++ (15.2.0-r5)
|
||||
#26 1.470 ( 4/22) Installing zstd-libs (1.6.0-r1)
|
||||
#26 1.567 ( 5/22) Installing binutils (2.45.1-r1)
|
||||
#26 1.775 ( 6/22) Installing libgcc-static (15.2.0-r5)
|
||||
#26 1.908 ( 7/22) Installing libgomp (15.2.0-r5)
|
||||
#26 1.997 ( 8/22) Installing libatomic (15.2.0-r5)
|
||||
#26 2.079 ( 9/22) Installing gmp (6.3.0-r4)
|
||||
#26 2.173 (10/22) Installing isl26 (0.26-r2)
|
||||
#26 2.294 (11/22) Installing mpfr4 (4.2.2-r0)
|
||||
#26 2.397 (12/22) Installing mpc1 (1.3.1-r1)
|
||||
#26 2.481 (13/22) Installing gcc (15.2.0-r5)
|
||||
#26 7.161 (14/22) Installing giflib (5.2.2-r2)
|
||||
#26 7.244 (15/22) Installing libjpeg-turbo (3.1.3-r0)
|
||||
#26 7.356 (16/22) Installing libpng (1.6.59-r0)
|
||||
#26 7.451 (17/22) Installing libsharpyuv (1.6.0-r0)
|
||||
#26 7.537 (18/22) Installing libwebp (1.6.0-r0)
|
||||
#26 7.648 (19/22) Installing libwebpdemux (1.6.0-r0)
|
||||
#26 7.731 (20/22) Installing libwebpmux (1.6.0-r0)
|
||||
#26 7.817 (21/22) Installing libwebp-tools (1.6.0-r0)
|
||||
#26 7.913 (22/22) Installing musl-dev (1.2.6-r3)
|
||||
#26 8.549 Executing busybox-1.37.0-r31.trigger
|
||||
#26 8.559 OK: 176.0 MiB in 39 packages
|
||||
#26 DONE 8.7s
|
||||
|
||||
#28 [tests tests 2/2] RUN --mount=type=cache,target=/go/pkg/mod mkdir -p /opt/gomod && cp -a /go/pkg/mod/. /opt/gomod/
|
||||
#28 DONE 2.9s
|
||||
|
||||
#29 [tests] exporting to image
|
||||
#29 exporting layers
|
||||
#29 exporting layers 11.2s done
|
||||
#29 exporting manifest sha256:665afab75275fe67682c6aff3ceac03216c264383bcee0f187bbc722ee677a66
|
||||
#29 exporting manifest sha256:665afab75275fe67682c6aff3ceac03216c264383bcee0f187bbc722ee677a66 0.0s done
|
||||
#29 exporting config sha256:fde951401451ecb2a9a786d48591dc2a74390a3de35021f179e91ecf9b35c915 0.0s done
|
||||
#29 exporting attestation manifest sha256:a5e086eb0a82ac80d98423f2730f3ac5eadb25c998c9c62c4cb454d30435bf31 0.0s done
|
||||
#29 exporting manifest list sha256:a7539c215a62520998a8acd12cc27cf15e89c335debde91f47afd650d9abb779 done
|
||||
#29 naming to docker.io/library/mtusi-messenger-tests:lab7 done
|
||||
#29 unpacking to docker.io/library/mtusi-messenger-tests:lab7
|
||||
#29 unpacking to docker.io/library/mtusi-messenger-tests:lab7 3.2s done
|
||||
#29 DONE 14.6s
|
||||
|
||||
#30 [tests] resolving provenance for metadata file
|
||||
#30 DONE 0.0s
|
||||
api Built
|
||||
tests Built
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,2 @@
|
||||
Rotated worker SQL secret and leaf certificate; previous serial denied; images unchanged; private values hidden.
|
||||
PASS: bounded worker compromise, before/after least privilege, actual identity/SQL revocation, fresh worker restored all accepted bytes; no image rebuild
|
||||
Binary file not shown.
@@ -0,0 +1,153 @@
|
||||
{
|
||||
"dependency-scan-initial": {
|
||||
"config": {
|
||||
"protocol_version": "v1.0.0",
|
||||
"scanner_name": "govulncheck",
|
||||
"scanner_version": "v1.10.0",
|
||||
"db": "https://vuln.go.dev",
|
||||
"db_last_modified": "2026-11-24T15:56:00Z",
|
||||
"go_version": "go1.27.4",
|
||||
"scan_level": "symbol",
|
||||
"scan_mode": "source"
|
||||
},
|
||||
"findings": 423,
|
||||
"called_advisory_count": 24,
|
||||
"called_advisories": [
|
||||
{
|
||||
"id": "GO-2023-1572",
|
||||
"summary": "Denial of service via crafted TIFF image in golang.org/x/image/tiff",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2023-1572"
|
||||
},
|
||||
{
|
||||
"id": "GO-2023-1989",
|
||||
"summary": "Excessive resource consumption in golang.org/x/image/tiff",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2023-1989"
|
||||
},
|
||||
{
|
||||
"id": "GO-2023-1990",
|
||||
"summary": "Excessive CPU consumption when decoding 0-height images in golang.org/x/image/tiff",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2023-1990"
|
||||
},
|
||||
{
|
||||
"id": "GO-2024-2937",
|
||||
"summary": "Panic when parsing invalid palette-color images in golang.org/x/image",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2024-2937"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-4394",
|
||||
"summary": "OpenTelemetry Go SDK Vulnerable to Arbitrary Code Execution via PATH Hijacking in go.opentelemetry.io/otel/sdk",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-4394"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-4815",
|
||||
"summary": "OOM from malicious IFD offset in golang.org/x/image/tiff",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-4815"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-4985",
|
||||
"summary": "Oversized OTLP HTTP response bodies can cause memory exhaustion in go.opentelemetry.io/otel/exporters/otlp",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-4985"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-5004",
|
||||
"summary": "SQL Injection via placeholder confusion with dollar quoted string literals in github.com/jackc/pgx",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-5004"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-5031",
|
||||
"summary": "Panic when reading out of bound palette index in golang.org/x/image/bmp",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-5031"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-5032",
|
||||
"summary": "Excessive resource consumption in PackBits decompression in golang.org/x/image/tiff",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-5032"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-5062",
|
||||
"summary": "Lack of limit on tile sizes in x/image/tiff in golang.org/x/image",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-5062"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-5066",
|
||||
"summary": "Panic decoding image with out-of-bounds strip offset in x/image/tiff in golang.org/x/image",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-5066"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-5506",
|
||||
"summary": "OpenTelemetry-Go: Multi-value baggage header extraction causes excessive allocations in go.opentelemetry.io/otel",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-5506"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-5970",
|
||||
"summary": "Infinite loop on invalid input in golang.org/x/text",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-5970"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-6061",
|
||||
"summary": "Vulnerabilities in the xDS RBAC authorization engine and the HTTP/2 transport server implementation in google.golang.org/grpc",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-6061"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-6348",
|
||||
"summary": "Heap Memory Exhaustion (OOM) via HTTP/2 DATA Frame Fragmentation in google.golang.org/grpc",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-6348"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-6505",
|
||||
"summary": "OpenTelemetry-Go: Exporter config logging may leak endpoint URLs in info logs in go.opentelemetry.io/otel/exporters/otlp/otlptrace",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-6505"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-6603",
|
||||
"summary": "HTTP/2 server memory exhaustion due to Trailer headers in net/http",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-6603"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-6611",
|
||||
"summary": "Excessive CPU consumption from repeated initial window changes in net/http",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-6611"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-6612",
|
||||
"summary": "Double flow control refund on HTTP/2 server streams in net/http",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-6612"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-6615",
|
||||
"summary": "OpenTelemetry-Go: BatchProcessor can busy-spin when export buffer is full in go.opentelemetry.io/otel/sdk/log",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-6615"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-6617",
|
||||
"summary": "HTTP/2 server crash due to HPACK encoder race in net/http",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-6617"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-6629",
|
||||
"summary": "Panic parsing crafted input in x/text/secure/precis in golang.org/x/text",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-6629"
|
||||
},
|
||||
{
|
||||
"id": "GO-2026-6974",
|
||||
"summary": "AttributeValueLengthLimit bypass via U+FFFD runes in go.opentelemetry.io/otel/sdk",
|
||||
"url": "https://pkg.go.dev/vuln/GO-2026-6974"
|
||||
}
|
||||
]
|
||||
},
|
||||
"dependency-scan": {
|
||||
"config": {
|
||||
"protocol_version": "v1.0.0",
|
||||
"scanner_name": "govulncheck",
|
||||
"scanner_version": "v1.10.0",
|
||||
"db": "https://vuln.go.dev",
|
||||
"db_last_modified": "2026-11-24T15:56:00Z",
|
||||
"go_version": "go1.27.4",
|
||||
"scan_level": "symbol",
|
||||
"scan_mode": "source"
|
||||
},
|
||||
"findings": 0,
|
||||
"called_advisory_count": 0,
|
||||
"called_advisories": []
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,74 @@
|
||||
go: downloading golang.org/x/net v0.63.0
|
||||
go: downloading google.golang.org/protobuf v1.36.12
|
||||
go: downloading go.opentelemetry.io/proto/otlp v1.11.0
|
||||
go: downloading github.com/cenkalti/backoff/v5 v5.0.3
|
||||
go: downloading go.opentelemetry.io/otel/log v1.47.0
|
||||
go: downloading github.com/go-logr/logr v1.4.4
|
||||
go: downloading go.opentelemetry.io/otel/metric v1.47.0
|
||||
go: downloading go.opentelemetry.io/otel/trace v1.47.0
|
||||
go: downloading go.opentelemetry.io/auto/sdk v1.2.1
|
||||
go: downloading go.opentelemetry.io/otel/sdk/metric v1.47.0
|
||||
go: downloading google.golang.org/grpc v1.83.2
|
||||
go: downloading golang.org/x/text v0.44.0
|
||||
go: downloading github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0
|
||||
go: downloading golang.org/x/sys v0.50.0
|
||||
go: downloading google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc
|
||||
go: downloading google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc
|
||||
go: downloading github.com/stretchr/testify v1.12.1
|
||||
go: downloading go.opentelemetry.io/otel/sdk/log/logtest v0.23.0
|
||||
go: upgraded github.com/cenkalti/backoff/v5 v5.0.2 => v5.0.3
|
||||
go: upgraded github.com/go-logr/logr v1.4.2 => v1.4.4
|
||||
go: upgraded github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 => v2.30.0
|
||||
go: upgraded github.com/jackc/pgx/v5 v5.7.6 => v5.9.2
|
||||
go: upgraded github.com/klauspost/compress v1.18.0 => v1.20.2
|
||||
go: upgraded go.opentelemetry.io/auto/sdk v1.1.0 => v1.2.1
|
||||
go: upgraded go.opentelemetry.io/otel v1.36.0 => v1.47.0
|
||||
go: upgraded go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.12.2 => v0.23.0
|
||||
go: upgraded go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.36.0 => v1.47.0
|
||||
go: upgraded go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.36.0 => v1.47.0
|
||||
go: upgraded go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.36.0 => v1.47.0
|
||||
go: upgraded go.opentelemetry.io/otel/log v0.12.2 => v1.47.0
|
||||
go: upgraded go.opentelemetry.io/otel/metric v1.36.0 => v1.47.0
|
||||
go: upgraded go.opentelemetry.io/otel/sdk v1.36.0 => v1.47.0
|
||||
go: upgraded go.opentelemetry.io/otel/sdk/log v0.12.2 => v1.47.0
|
||||
go: upgraded go.opentelemetry.io/otel/sdk/metric v1.36.0 => v1.47.0
|
||||
go: upgraded go.opentelemetry.io/otel/trace v1.36.0 => v1.47.0
|
||||
go: upgraded go.opentelemetry.io/proto/otlp v1.6.0 => v1.11.0
|
||||
go: upgraded golang.org/x/crypto v0.41.0 => v0.59.0
|
||||
go: upgraded golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 => v0.45.0
|
||||
go: upgraded golang.org/x/net v0.42.0 => v0.63.0
|
||||
go: upgraded golang.org/x/sync v0.16.0 => v0.25.0
|
||||
go: upgraded golang.org/x/sys v0.35.0 => v0.50.0
|
||||
go: upgraded golang.org/x/text v0.28.0 => v0.44.0
|
||||
go: upgraded google.golang.org/genproto/googleapis/api v0.0.0-20250519155744-55703ea1f237 => v0.0.0-20260928230214-8a89bd6388cc
|
||||
go: upgraded google.golang.org/genproto/googleapis/rpc v0.0.0-20250519155744-55703ea1f237 => v0.0.0-20260928230214-8a89bd6388cc
|
||||
go: upgraded google.golang.org/grpc v1.72.1 => v1.83.2
|
||||
go: upgraded google.golang.org/protobuf v1.36.6 => v1.36.12
|
||||
go: downloading github.com/google/go-cmp v0.7.0
|
||||
go: downloading go.opentelemetry.io/otel/metric/x v0.69.0
|
||||
go: downloading go.uber.org/goleak v1.3.0
|
||||
go: downloading github.com/golang/protobuf v1.5.4
|
||||
go: downloading github.com/bsm/ginkgo/v2 v2.12.0
|
||||
go: downloading github.com/bsm/gomega v1.27.10
|
||||
go: downloading gonum.org/v1/gonum v0.17.0
|
||||
go: downloading go.yaml.in/yaml/v3 v3.0.5
|
||||
# go.opentelemetry.io/contrib/bridges/otelslog
|
||||
/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/handler.go:347:37: undefined: log.KeyValue
|
||||
/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/handler.go:380:13: undefined: log.KeyValue
|
||||
/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/handler.go:404:41: undefined: log.KeyValue
|
||||
/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/handler.go:452:32: undefined: log.Value
|
||||
/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:20:30: undefined: log.Value
|
||||
/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:24:14: undefined: log.BoolValue
|
||||
/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:26:14: undefined: log.StringValue
|
||||
/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:28:14: undefined: log.Int64Value
|
||||
/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:30:14: undefined: log.Int64Value
|
||||
/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:118:37: undefined: log.Value
|
||||
/go/pkg/mod/go.opentelemetry.io/contrib/bridges/otelslog@v0.11.0/convert.go:30:14: too many errors
|
||||
? mtusi/messenger/internal/security [no test files]
|
||||
FAIL mtusi/messenger/cmd/server [build failed]
|
||||
FAIL
|
||||
go: downloading go.opentelemetry.io/contrib v1.47.0
|
||||
go: downloading go.opentelemetry.io/contrib/bridges/otelslog v0.21.0
|
||||
go: upgraded go.opentelemetry.io/contrib/bridges/otelslog v0.11.0 => v0.21.0
|
||||
? mtusi/messenger/internal/security [no test files]
|
||||
? mtusi/messenger/cmd/server [no test files]
|
||||
@@ -0,0 +1,118 @@
|
||||
mtusi/messenger
|
||||
cel.dev/expr v0.25.2
|
||||
cloud.google.com/go/auth v0.18.2
|
||||
cloud.google.com/go/compute/metadata v0.9.0
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0
|
||||
github.com/apapsch/go-jsonmerge/v2 v2.0.0
|
||||
github.com/bsm/ginkgo/v2 v2.12.0
|
||||
github.com/bsm/gomega v1.27.10
|
||||
github.com/cenkalti/backoff/v5 v5.0.3
|
||||
github.com/cespare/xxhash/v2 v2.3.0
|
||||
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2
|
||||
github.com/davecgh/go-spew v1.1.1
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f
|
||||
github.com/disintegration/imaging v1.6.2
|
||||
github.com/dustin/go-humanize v1.0.1
|
||||
github.com/envoyproxy/go-control-plane v0.14.0
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.37.0
|
||||
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3
|
||||
github.com/felixge/httpsnoop v1.1.0
|
||||
github.com/go-ini/ini v1.67.0
|
||||
github.com/go-jose/go-jose/v4 v4.1.4
|
||||
github.com/go-logr/logr v1.4.4
|
||||
github.com/go-logr/stdr v1.2.2
|
||||
github.com/go-openapi/analysis v0.25.5
|
||||
github.com/go-openapi/errors v0.22.8
|
||||
github.com/go-openapi/jsonpointer v1.0.0
|
||||
github.com/go-openapi/jsonreference v1.0.0
|
||||
github.com/go-openapi/loads v0.25.0
|
||||
github.com/go-openapi/runtime v0.33.0
|
||||
github.com/go-openapi/runtime/server-middleware v0.30.0
|
||||
github.com/go-openapi/spec v0.22.9
|
||||
github.com/go-openapi/strfmt v0.27.0
|
||||
github.com/go-openapi/swag v0.28.0
|
||||
github.com/go-openapi/swag/cmdutils v0.28.0
|
||||
github.com/go-openapi/swag/conv v0.28.0
|
||||
github.com/go-openapi/swag/fileutils v0.28.0
|
||||
github.com/go-openapi/swag/jsonutils v0.28.0
|
||||
github.com/go-openapi/swag/loading v0.28.0
|
||||
github.com/go-openapi/swag/mangling v0.28.0
|
||||
github.com/go-openapi/swag/netutils v0.28.0
|
||||
github.com/go-openapi/swag/pools v0.28.0
|
||||
github.com/go-openapi/swag/stringutils v0.28.0
|
||||
github.com/go-openapi/swag/typeutils v0.28.0
|
||||
github.com/go-openapi/swag/yamlutils v0.28.0
|
||||
github.com/go-openapi/validate v0.26.1
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0
|
||||
github.com/goccy/go-json v0.10.5
|
||||
github.com/golang/glog v1.2.5
|
||||
github.com/golang/protobuf v1.5.4
|
||||
github.com/google/go-cmp v0.7.0
|
||||
github.com/google/s2a-go v0.1.9
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.11
|
||||
github.com/googleapis/gax-go/v2 v2.17.0
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0
|
||||
github.com/jackc/pgpassfile v1.0.0
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761
|
||||
github.com/jackc/pgx/v5 v5.9.2
|
||||
github.com/jackc/puddle/v2 v2.2.2
|
||||
github.com/klauspost/compress v1.20.2
|
||||
github.com/klauspost/cpuid/v2 v2.2.11
|
||||
github.com/kr/pretty v0.3.1
|
||||
github.com/minio/crc64nvme v1.0.2
|
||||
github.com/minio/md5-simd v1.1.2
|
||||
github.com/minio/minio-go/v7 v7.0.95
|
||||
github.com/oapi-codegen/runtime v1.6.0
|
||||
github.com/oklog/ulid/v2 v2.1.1
|
||||
github.com/philhofer/fwd v1.2.0
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10
|
||||
github.com/pmezard/go-difflib v1.0.0
|
||||
github.com/redis/go-redis/v9 v9.12.1
|
||||
github.com/rogpeppe/fastuuid v1.2.0
|
||||
github.com/rogpeppe/go-internal v1.14.1
|
||||
github.com/rs/xid v1.6.0
|
||||
github.com/spiffe/go-spiffe/v2 v2.7.0
|
||||
github.com/stretchr/objx v0.1.0
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/tinylib/msgp v1.3.0
|
||||
go.opentelemetry.io/auto/sdk v1.2.1
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.44.0
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0
|
||||
go.opentelemetry.io/otel v1.47.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.45.0
|
||||
go.opentelemetry.io/otel/log v1.47.0
|
||||
go.opentelemetry.io/otel/metric v1.47.0
|
||||
go.opentelemetry.io/otel/metric/x v0.69.0
|
||||
go.opentelemetry.io/otel/sdk v1.47.0
|
||||
go.opentelemetry.io/otel/sdk/log v1.47.0
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.23.0
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0
|
||||
go.opentelemetry.io/otel/trace v1.47.0
|
||||
go.opentelemetry.io/proto/otlp v1.11.0
|
||||
go.uber.org/goleak v1.3.0
|
||||
go.yaml.in/yaml/v3 v3.0.5
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/image v0.45.0
|
||||
golang.org/x/mod v0.42.0
|
||||
golang.org/x/net v0.63.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sync v0.25.0
|
||||
golang.org/x/sys v0.50.0
|
||||
golang.org/x/term v0.48.0
|
||||
golang.org/x/text v0.44.0
|
||||
golang.org/x/tools v0.52.0
|
||||
gonum.org/v1/gonum v0.17.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc
|
||||
google.golang.org/grpc v1.83.2
|
||||
google.golang.org/protobuf v1.36.12
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
@@ -0,0 +1,4 @@
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "https://localhost:8443" --ca-file "/Users/glebkraykin/Projects/highload-apps-labs/lab7/certs/ca.crt"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 110, "failed_attempts": 1, "first_recovery_seconds": 1.149}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,505 @@
|
||||
{
|
||||
"runtime": [
|
||||
{
|
||||
"service": "api",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 805306368,
|
||||
"nano_cpus_limit": 1000000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:19:37.993962054Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "api",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 805306368,
|
||||
"nano_cpus_limit": 1000000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:10:41.942116375Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "broker",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 134217728,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:10:38.562146138Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "broker-store",
|
||||
"user": "999:1000",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 268435456,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773",
|
||||
"started_at": "2026-12-02T14:10:38.722964263Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "cache",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 134217728,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:10:38.577258679Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "cache-store",
|
||||
"user": "999:1000",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 268435456,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773",
|
||||
"started_at": "2026-12-02T14:10:38.753695763Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "collector",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 134217728,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:10:38.574985221Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "collector-store",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 268435456,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:1ab0baba0ee3695d823c46653d8a6e8894896e668ce8bd7ebe002e948d827bc7",
|
||||
"started_at": "2026-12-02T14:10:38.874202929Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "dispatcher",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 134217728,
|
||||
"nano_cpus_limit": 250000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:10:41.933912166Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "grafana",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 134217728,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:10:38.559359388Z",
|
||||
"published_ports": {
|
||||
"3000/tcp": [
|
||||
{
|
||||
"HostIp": "127.0.0.1",
|
||||
"HostPort": "3007"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"service": "grafana-store",
|
||||
"user": "472",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 268435456,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:b5b59bfc7561634c2d7b136c4543d702ebcc94a3da477f21ff26f89ffd4214fa",
|
||||
"started_at": "2026-12-02T14:10:38.755523763Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "housekeeping",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 134217728,
|
||||
"nano_cpus_limit": 250000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:10:41.941801375Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "lb",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 134217728,
|
||||
"nano_cpus_limit": 1000000000,
|
||||
"image_id": "sha256:3a819392f5a6af2a9203d1c63ff0feba74f0c940623a558511be06d7d85e361c",
|
||||
"started_at": "2026-12-02T14:10:42.1189875Z",
|
||||
"published_ports": {
|
||||
"8443/tcp": [
|
||||
{
|
||||
"HostIp": "127.0.0.1",
|
||||
"HostPort": "8443"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"service": "loki",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 134217728,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:10:38.581135971Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "loki-store",
|
||||
"user": "10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 268435456,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:a74594532eec4cc313401beedc4dd2708c43674c032084b1aeb87c14a5be1745",
|
||||
"started_at": "2026-12-02T14:10:38.840854804Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "openbao",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 268435456,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9",
|
||||
"started_at": "2026-12-02T14:10:39.320626388Z",
|
||||
"published_ports": {
|
||||
"8200/tcp": [
|
||||
{
|
||||
"HostIp": "127.0.0.1",
|
||||
"HostPort": "8207"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"service": "postgres",
|
||||
"user": "",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": [
|
||||
"CAP_CHOWN",
|
||||
"CAP_DAC_OVERRIDE",
|
||||
"CAP_FOWNER",
|
||||
"CAP_SETGID",
|
||||
"CAP_SETUID"
|
||||
],
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 536870912,
|
||||
"nano_cpus_limit": 2000000000,
|
||||
"image_id": "sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94",
|
||||
"started_at": "2026-12-02T14:10:38.582143221Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "prometheus",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 134217728,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:10:38.491951637Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "prometheus-store",
|
||||
"user": "nobody",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 268435456,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:9abc6cf6aea7710d163dbb28d8eeb7dc5baef01e38fa4cd146a406dd9f07f70d",
|
||||
"started_at": "2026-12-02T14:10:38.673212388Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "s3",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 134217728,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:10:38.572567096Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "s3-store",
|
||||
"user": "",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 536870912,
|
||||
"nano_cpus_limit": 1000000000,
|
||||
"image_id": "sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e",
|
||||
"started_at": "2026-12-02T14:10:38.783305721Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "tempo",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 134217728,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:10:38.500782637Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "tempo-store",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 268435456,
|
||||
"nano_cpus_limit": 500000000,
|
||||
"image_id": "sha256:3cbb1b4eae79b158d25006d88abadb1f87ef98f8a902cd54c3bdffff78ea6cda",
|
||||
"started_at": "2026-12-02T14:10:38.655961679Z",
|
||||
"published_ports": {}
|
||||
},
|
||||
{
|
||||
"service": "worker",
|
||||
"user": "10001:10001",
|
||||
"read_only": true,
|
||||
"drop_capabilities": [
|
||||
"ALL"
|
||||
],
|
||||
"add_capabilities": null,
|
||||
"security_options": [
|
||||
"no-new-privileges:true"
|
||||
],
|
||||
"memory_limit_bytes": 1073741824,
|
||||
"nano_cpus_limit": 1000000000,
|
||||
"image_id": "sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245",
|
||||
"started_at": "2026-12-02T14:19:31.736994051Z",
|
||||
"published_ports": {}
|
||||
}
|
||||
],
|
||||
"no_native_bypass": [
|
||||
{
|
||||
"service": "api",
|
||||
"native_port": 8081,
|
||||
"external_namespace_connection_denied": true
|
||||
},
|
||||
{
|
||||
"service": "broker",
|
||||
"native_port": 6380,
|
||||
"external_namespace_connection_denied": true
|
||||
},
|
||||
{
|
||||
"service": "cache",
|
||||
"native_port": 6380,
|
||||
"external_namespace_connection_denied": true
|
||||
},
|
||||
{
|
||||
"service": "s3",
|
||||
"native_port": 9001,
|
||||
"external_namespace_connection_denied": true
|
||||
},
|
||||
{
|
||||
"service": "s3",
|
||||
"native_port": 9002,
|
||||
"external_namespace_connection_denied": true
|
||||
},
|
||||
{
|
||||
"service": "collector",
|
||||
"native_port": 4319,
|
||||
"external_namespace_connection_denied": true
|
||||
},
|
||||
{
|
||||
"service": "collector",
|
||||
"native_port": 8890,
|
||||
"external_namespace_connection_denied": true
|
||||
},
|
||||
{
|
||||
"service": "prometheus",
|
||||
"native_port": 9091,
|
||||
"external_namespace_connection_denied": true
|
||||
},
|
||||
{
|
||||
"service": "loki",
|
||||
"native_port": 3101,
|
||||
"external_namespace_connection_denied": true
|
||||
},
|
||||
{
|
||||
"service": "tempo",
|
||||
"native_port": 3201,
|
||||
"external_namespace_connection_denied": true
|
||||
},
|
||||
{
|
||||
"service": "grafana",
|
||||
"native_port": 3001,
|
||||
"external_namespace_connection_denied": true
|
||||
}
|
||||
],
|
||||
"worker_filesystem": {
|
||||
"rootfs_write": "denied",
|
||||
"operator_key": "denied",
|
||||
"other_identity": "denied"
|
||||
},
|
||||
"worker_effective_caps_zero": true,
|
||||
"worker_no_new_privileges": true,
|
||||
"known_private_values_absent_from_config_env_and_sampled_logs": true,
|
||||
"scope": "runtime containers only; verify-profile compiler/operator tools not persistent runtime; last500 app/collector log lines sampled, not proof of all future logs"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
PASS: actual non-root/capabilities/read-only/ports, closed native hops, scoped worker mounts and sampled private-value scan
|
||||
@@ -0,0 +1,314 @@
|
||||
{
|
||||
"requested_duration_seconds": 15,
|
||||
"concurrency": 4,
|
||||
"warmup_seconds": 0,
|
||||
"before": {
|
||||
"users": 35,
|
||||
"chats": 13,
|
||||
"messages": 609,
|
||||
"attachments": 16
|
||||
},
|
||||
"after": {
|
||||
"users": 38,
|
||||
"chats": 14,
|
||||
"messages": 2995,
|
||||
"attachments": 16
|
||||
},
|
||||
"resource_observations": [
|
||||
{
|
||||
"elapsed_seconds": 1.771,
|
||||
"containers": [
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "42.59%",
|
||||
"Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8",
|
||||
"ID": "184f26c3f953",
|
||||
"MemPerc": "21.90%",
|
||||
"MemUsage": "168.2MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-1",
|
||||
"NetIO": "1.15MB / 1.62MB",
|
||||
"PIDs": "16"
|
||||
},
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "41.75%",
|
||||
"Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec",
|
||||
"ID": "83ebe4343681",
|
||||
"MemPerc": "18.43%",
|
||||
"MemUsage": "141.6MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-2",
|
||||
"NetIO": "252kB / 323kB",
|
||||
"PIDs": "15"
|
||||
},
|
||||
{
|
||||
"BlockIO": "3.23MB / 0B",
|
||||
"CPUPerc": "1.07%",
|
||||
"Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a",
|
||||
"ID": "7703854ae2b9",
|
||||
"MemPerc": "27.97%",
|
||||
"MemUsage": "71.61MiB / 256MiB",
|
||||
"Name": "mtusi-lab7-kraykin-collector-store-1",
|
||||
"NetIO": "13.7MB / 8.39MB",
|
||||
"PIDs": "19"
|
||||
},
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "0.03%",
|
||||
"Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4",
|
||||
"ID": "71cbb9cee6bb",
|
||||
"MemPerc": "1.70%",
|
||||
"MemUsage": "17.4MiB / 1GiB",
|
||||
"Name": "mtusi-lab7-kraykin-worker-1",
|
||||
"NetIO": "1.65MB / 2.39MB",
|
||||
"PIDs": "17"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"elapsed_seconds": 4.804,
|
||||
"containers": [
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "15.93%",
|
||||
"Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8",
|
||||
"ID": "184f26c3f953",
|
||||
"MemPerc": "22.06%",
|
||||
"MemUsage": "169.4MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-1",
|
||||
"NetIO": "2.81MB / 3.99MB",
|
||||
"PIDs": "16"
|
||||
},
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "29.32%",
|
||||
"Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec",
|
||||
"ID": "83ebe4343681",
|
||||
"MemPerc": "2.75%",
|
||||
"MemUsage": "21.13MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-2",
|
||||
"NetIO": "3.07MB / 4.39MB",
|
||||
"PIDs": "15"
|
||||
},
|
||||
{
|
||||
"BlockIO": "3.23MB / 0B",
|
||||
"CPUPerc": "2.66%",
|
||||
"Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a",
|
||||
"ID": "7703854ae2b9",
|
||||
"MemPerc": "27.98%",
|
||||
"MemUsage": "71.63MiB / 256MiB",
|
||||
"Name": "mtusi-lab7-kraykin-collector-store-1",
|
||||
"NetIO": "14.8MB / 8.75MB",
|
||||
"PIDs": "19"
|
||||
},
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "0.52%",
|
||||
"Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4",
|
||||
"ID": "71cbb9cee6bb",
|
||||
"MemPerc": "1.70%",
|
||||
"MemUsage": "17.43MiB / 1GiB",
|
||||
"Name": "mtusi-lab7-kraykin-worker-1",
|
||||
"NetIO": "1.66MB / 2.4MB",
|
||||
"PIDs": "17"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"elapsed_seconds": 7.836,
|
||||
"containers": [
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "24.06%",
|
||||
"Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8",
|
||||
"ID": "184f26c3f953",
|
||||
"MemPerc": "5.34%",
|
||||
"MemUsage": "41.02MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-1",
|
||||
"NetIO": "6.07MB / 8.76MB",
|
||||
"PIDs": "16"
|
||||
},
|
||||
{
|
||||
"BlockIO": "193kB / 0B",
|
||||
"CPUPerc": "3.34%",
|
||||
"Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec",
|
||||
"ID": "83ebe4343681",
|
||||
"MemPerc": "2.66%",
|
||||
"MemUsage": "20.4MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-2",
|
||||
"NetIO": "5.25MB / 7.57MB",
|
||||
"PIDs": "16"
|
||||
},
|
||||
{
|
||||
"BlockIO": "3.23MB / 0B",
|
||||
"CPUPerc": "1.03%",
|
||||
"Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a",
|
||||
"ID": "7703854ae2b9",
|
||||
"MemPerc": "28.68%",
|
||||
"MemUsage": "73.43MiB / 256MiB",
|
||||
"Name": "mtusi-lab7-kraykin-collector-store-1",
|
||||
"NetIO": "17MB / 9.52MB",
|
||||
"PIDs": "19"
|
||||
},
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "0.38%",
|
||||
"Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4",
|
||||
"ID": "71cbb9cee6bb",
|
||||
"MemPerc": "1.71%",
|
||||
"MemUsage": "17.47MiB / 1GiB",
|
||||
"Name": "mtusi-lab7-kraykin-worker-1",
|
||||
"NetIO": "1.66MB / 2.4MB",
|
||||
"PIDs": "17"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"elapsed_seconds": 10.883,
|
||||
"containers": [
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "3.61%",
|
||||
"Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8",
|
||||
"ID": "184f26c3f953",
|
||||
"MemPerc": "5.25%",
|
||||
"MemUsage": "40.3MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-1",
|
||||
"NetIO": "6.41MB / 9.28MB",
|
||||
"PIDs": "16"
|
||||
},
|
||||
{
|
||||
"BlockIO": "193kB / 0B",
|
||||
"CPUPerc": "2.80%",
|
||||
"Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec",
|
||||
"ID": "83ebe4343681",
|
||||
"MemPerc": "2.62%",
|
||||
"MemUsage": "20.16MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-2",
|
||||
"NetIO": "5.42MB / 7.83MB",
|
||||
"PIDs": "16"
|
||||
},
|
||||
{
|
||||
"BlockIO": "3.23MB / 0B",
|
||||
"CPUPerc": "2.86%",
|
||||
"Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a",
|
||||
"ID": "7703854ae2b9",
|
||||
"MemPerc": "27.22%",
|
||||
"MemUsage": "69.68MiB / 256MiB",
|
||||
"Name": "mtusi-lab7-kraykin-collector-store-1",
|
||||
"NetIO": "17.2MB / 9.6MB",
|
||||
"PIDs": "19"
|
||||
},
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "0.57%",
|
||||
"Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4",
|
||||
"ID": "71cbb9cee6bb",
|
||||
"MemPerc": "1.71%",
|
||||
"MemUsage": "17.51MiB / 1GiB",
|
||||
"Name": "mtusi-lab7-kraykin-worker-1",
|
||||
"NetIO": "1.67MB / 2.41MB",
|
||||
"PIDs": "17"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"elapsed_seconds": 13.927,
|
||||
"containers": [
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "2.66%",
|
||||
"Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8",
|
||||
"ID": "184f26c3f953",
|
||||
"MemPerc": "5.25%",
|
||||
"MemUsage": "40.29MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-1",
|
||||
"NetIO": "6.57MB / 9.51MB",
|
||||
"PIDs": "16"
|
||||
},
|
||||
{
|
||||
"BlockIO": "193kB / 0B",
|
||||
"CPUPerc": "4.57%",
|
||||
"Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec",
|
||||
"ID": "83ebe4343681",
|
||||
"MemPerc": "2.86%",
|
||||
"MemUsage": "21.99MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-2",
|
||||
"NetIO": "5.76MB / 8.34MB",
|
||||
"PIDs": "16"
|
||||
},
|
||||
{
|
||||
"BlockIO": "3.23MB / 0B",
|
||||
"CPUPerc": "0.88%",
|
||||
"Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a",
|
||||
"ID": "7703854ae2b9",
|
||||
"MemPerc": "27.64%",
|
||||
"MemUsage": "70.75MiB / 256MiB",
|
||||
"Name": "mtusi-lab7-kraykin-collector-store-1",
|
||||
"NetIO": "17.4MB / 9.68MB",
|
||||
"PIDs": "19"
|
||||
},
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "0.31%",
|
||||
"Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4",
|
||||
"ID": "71cbb9cee6bb",
|
||||
"MemPerc": "1.74%",
|
||||
"MemUsage": "17.81MiB / 1GiB",
|
||||
"Name": "mtusi-lab7-kraykin-worker-1",
|
||||
"NetIO": "1.67MB / 2.42MB",
|
||||
"PIDs": "17"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"elapsed_seconds": 16.977,
|
||||
"containers": [
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "3.25%",
|
||||
"Container": "184f26c3f9536942f2fd500a9a9ab1a281d3790d640de4bc30a6cef3181dc4f8",
|
||||
"ID": "184f26c3f953",
|
||||
"MemPerc": "5.25%",
|
||||
"MemUsage": "40.3MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-1",
|
||||
"NetIO": "6.84MB / 9.91MB",
|
||||
"PIDs": "16"
|
||||
},
|
||||
{
|
||||
"BlockIO": "193kB / 0B",
|
||||
"CPUPerc": "4.92%",
|
||||
"Container": "83ebe4343681af3d3dd6f2f50ff94f6e58ab419818b62255134cfed1b1606dec",
|
||||
"ID": "83ebe4343681",
|
||||
"MemPerc": "2.88%",
|
||||
"MemUsage": "22.09MiB / 768MiB",
|
||||
"Name": "mtusi-lab7-kraykin-api-2",
|
||||
"NetIO": "6.11MB / 8.83MB",
|
||||
"PIDs": "16"
|
||||
},
|
||||
{
|
||||
"BlockIO": "3.23MB / 0B",
|
||||
"CPUPerc": "1.40%",
|
||||
"Container": "7703854ae2b9a7d08fd7dc0cb9fac556b99f38527c3fc3165bbdda3972b3b68a",
|
||||
"ID": "7703854ae2b9",
|
||||
"MemPerc": "27.64%",
|
||||
"MemUsage": "70.75MiB / 256MiB",
|
||||
"Name": "mtusi-lab7-kraykin-collector-store-1",
|
||||
"NetIO": "17.6MB / 9.77MB",
|
||||
"PIDs": "19"
|
||||
},
|
||||
{
|
||||
"BlockIO": "0B / 0B",
|
||||
"CPUPerc": "0.33%",
|
||||
"Container": "71cbb9cee6bb46d0821c70ab92547aa783c85939ff465ee6f179e49377e8b9d4",
|
||||
"ID": "71cbb9cee6bb",
|
||||
"MemPerc": "1.72%",
|
||||
"MemUsage": "17.57MiB / 1GiB",
|
||||
"Name": "mtusi-lab7-kraykin-worker-1",
|
||||
"NetIO": "1.68MB / 2.43MB",
|
||||
"PIDs": "17"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"limits": "closed-loop/coordinated omission, success-only latency percentiles, shared VM, growing dataset; no capacity or TLS off/on comparison"
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 7,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 15.0,
|
||||
"elapsed_seconds": 15.01,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 2386,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 158.96,
|
||||
"successful_latency_ms": {
|
||||
"p50": 8.173,
|
||||
"p95": 129.663,
|
||||
"p99": 196.474
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"lab": 7,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 15.0,
|
||||
"elapsed_seconds": 15.01,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 2386,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 158.96,
|
||||
"successful_latency_ms": {
|
||||
"p50": 8.173,
|
||||
"p95": 129.663,
|
||||
"p99": 196.474
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
MEASURED: verified HTTPS workload, errors, percentiles, CPU/RAM and dataset counts
|
||||
@@ -0,0 +1,4 @@
|
||||
/private/tmp/highload7-verify/bin/python scripts/validate_openapi.py
|
||||
/private/tmp/highload7-verify/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
|
||||
warnings.warn(
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
@@ -0,0 +1,46 @@
|
||||
[
|
||||
{
|
||||
"role": "api",
|
||||
"ttl_seconds": 60,
|
||||
"own_read": true,
|
||||
"denied_paths": [
|
||||
"kv/data/worker",
|
||||
"sys/policies/acl/escalation",
|
||||
"sys/raw/core"
|
||||
],
|
||||
"revoked_token_denied": true
|
||||
},
|
||||
{
|
||||
"role": "worker",
|
||||
"ttl_seconds": 60,
|
||||
"own_read": true,
|
||||
"denied_paths": [
|
||||
"kv/data/api",
|
||||
"sys/policies/acl/escalation",
|
||||
"sys/raw/core"
|
||||
],
|
||||
"revoked_token_denied": true
|
||||
},
|
||||
{
|
||||
"role": "dispatcher",
|
||||
"ttl_seconds": 60,
|
||||
"own_read": true,
|
||||
"denied_paths": [
|
||||
"kv/data/api",
|
||||
"sys/policies/acl/escalation",
|
||||
"sys/raw/core"
|
||||
],
|
||||
"revoked_token_denied": true
|
||||
},
|
||||
{
|
||||
"role": "housekeeping",
|
||||
"ttl_seconds": 60,
|
||||
"own_read": true,
|
||||
"denied_paths": [
|
||||
"kv/data/api",
|
||||
"sys/policies/acl/escalation",
|
||||
"sys/raw/core"
|
||||
],
|
||||
"revoked_token_denied": true
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"failures": [
|
||||
{
|
||||
"successful_writes": 148,
|
||||
"errors": 1,
|
||||
"successful_rps": 17.529176246121644,
|
||||
"first_recovery_seconds": 1.118,
|
||||
"action_seconds": 0.258,
|
||||
"instances": [
|
||||
"4e1905fc-f951-4020-b910-d8ef3ccfdeea",
|
||||
"7c6edd04-09c4-48cc-993d-87981c6277ab"
|
||||
],
|
||||
"confirmed_preserved": true,
|
||||
"stopped_alias": "7c6edd04-09c4-48cc-993d-87981c6277ab"
|
||||
},
|
||||
{
|
||||
"successful_writes": 143,
|
||||
"errors": 2,
|
||||
"successful_rps": 16.77245908330838,
|
||||
"first_recovery_seconds": 0.306,
|
||||
"action_seconds": 0.29,
|
||||
"instances": [
|
||||
"032ca595-80b4-48ed-b90d-2c36098714e5",
|
||||
"4e1905fc-f951-4020-b910-d8ef3ccfdeea"
|
||||
],
|
||||
"confirmed_preserved": true,
|
||||
"stopped_alias": "4e1905fc-f951-4020-b910-d8ef3ccfdeea"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
PASS: both API replicas stopped sequentially through verified HTTPS; confirmed writes preserved
|
||||
@@ -0,0 +1,3 @@
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "https://localhost:8443" --ca-file "/Users/glebkraykin/Projects/highload-apps-labs/lab7/certs/ca.crt"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/security.py --base-url "https://localhost:8443" --ca-file "/Users/glebkraykin/Projects/highload-apps-labs/lab7/certs/ca.crt"
|
||||
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||
@@ -0,0 +1,21 @@
|
||||
? mtusi/messenger/cmd/server [no test files]
|
||||
? mtusi/messenger/internal/database [no test files]
|
||||
=== RUN TestDatabaseConcurrentHTTP
|
||||
database_test.go:162: 100 confirmed messages from 10 clients through real HTTP and PostgreSQL; race detector enabled
|
||||
--- PASS: TestDatabaseConcurrentHTTP (1.99s)
|
||||
=== RUN TestPasswordFullUnicodeRange
|
||||
--- PASS: TestPasswordFullUnicodeRange (2.23s)
|
||||
=== RUN TestLegacyArgon2RehashOnHTTPLogin
|
||||
--- PASS: TestLegacyArgon2RehashOnHTTPLogin (2.35s)
|
||||
=== RUN TestTransformFailureClassification
|
||||
--- PASS: TestTransformFailureClassification (0.00s)
|
||||
=== RUN TestFitFloorNoUpscale
|
||||
--- PASS: TestFitFloorNoUpscale (0.00s)
|
||||
=== RUN TestTransformAlphaAndEXIF
|
||||
--- PASS: TestTransformAlphaAndEXIF (0.22s)
|
||||
=== RUN TestPNGEXIFAndMalformedIFD
|
||||
--- PASS: TestPNGEXIFAndMalformedIFD (0.11s)
|
||||
PASS
|
||||
ok mtusi/messenger/internal/messenger 7.932s
|
||||
? mtusi/messenger/internal/security [no test files]
|
||||
? mtusi/messenger/internal/telemetry [no test files]
|
||||
@@ -0,0 +1,8 @@
|
||||
Container mtusi-lab7-kraykin-api-1 Created
|
||||
Container mtusi-lab7-kraykin-api-2 Running
|
||||
Container mtusi-lab7-kraykin-api-1 Starting
|
||||
Container mtusi-lab7-kraykin-api-1 Started
|
||||
Container mtusi-lab7-kraykin-api-2 Waiting
|
||||
Container mtusi-lab7-kraykin-api-1 Waiting
|
||||
Container mtusi-lab7-kraykin-api-2 Healthy
|
||||
Container mtusi-lab7-kraykin-api-1 Healthy
|
||||
@@ -0,0 +1,150 @@
|
||||
{
|
||||
"expired_correct_identity_leaf": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"sealed_timeline": [
|
||||
{
|
||||
"seconds": 1.42,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 3.435,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 5.495,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 7.532,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 9.555,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 11.608,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 13.635,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 15.718,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 17.746,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 19.83,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 21.852,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 23.921,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 25.991,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 28.05,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 30.101,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 32.167,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 34.196,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 36.259,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 38.281,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 40.304,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 42.328,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 44.362,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 46.421,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 48.456,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 50.491,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 52.516,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 54.613,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 56.638,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 58.671,
|
||||
"http_status": 200
|
||||
},
|
||||
{
|
||||
"seconds": 60.698,
|
||||
"http_status": 503
|
||||
},
|
||||
{
|
||||
"seconds": 62.766,
|
||||
"http_status": 503
|
||||
},
|
||||
{
|
||||
"seconds": 64.775,
|
||||
"http_status": 503
|
||||
},
|
||||
{
|
||||
"seconds": 66.824,
|
||||
"http_status": 503
|
||||
}
|
||||
],
|
||||
"authorization_ttl_seconds": 60,
|
||||
"poll_seconds": 5,
|
||||
"observation_step_seconds": 2,
|
||||
"restarted_one_api_while_sealed": true,
|
||||
"restart_had_no_static_secret_fallback": true,
|
||||
"all_api_unavailable_observed_seconds": 60.698,
|
||||
"recovery_seconds_after_unseal": 4.324,
|
||||
"same_user_token_valid": true,
|
||||
"original_identical": true,
|
||||
"limits": "successful secret-read authorization cached until60s, refresh attempt timeout<=3s and loop5s; external TLS remains required; local single Bao fails closed after bounded cache"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
PASS: expired correct-SAN leaf rejected; sealed Bao bounds authorization, restarted API has no fallback, operator unseal restores same session/file
|
||||
@@ -0,0 +1,4 @@
|
||||
PASS: every API replica, broker, Collector and backend trust matrix; real TLS verification failures
|
||||
PASS: actual scoped OpenBao read/deny, short TTL, token revocation, forbidden identity
|
||||
PASS: attachment ACL, forged header, cross-chat link, expiry/logout, password/token hashes
|
||||
PASS: shared rate limit across two replicas with429/Retry-After; measured KDF budget
|
||||
@@ -0,0 +1,2 @@
|
||||
python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/Users/glebkraykin/Projects/highload-apps-labs/lab7/certs/ca.crt"
|
||||
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,206 @@
|
||||
Operator bootstrap complete; private values hidden; existing identities preserved.
|
||||
Compose can now delegate builds to bake for better performance.
|
||||
To do so, set COMPOSE_BAKE=true.
|
||||
#0 building with "desktop-linux" instance using docker driver
|
||||
|
||||
#1 [api internal] load build definition from Dockerfile
|
||||
#1 transferring dockerfile: 1.11kB done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [api internal] load metadata for docker.io/library/alpine:3.24.4
|
||||
#2 DONE 0.0s
|
||||
|
||||
#3 [api internal] load metadata for docker.io/library/golang:1.27.4-alpine3.24
|
||||
#3 DONE 0.0s
|
||||
|
||||
#4 [api internal] load .dockerignore
|
||||
#4 transferring context: 196B done
|
||||
#4 DONE 0.0s
|
||||
|
||||
#5 [api build 1/7] FROM docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280
|
||||
#5 resolve docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 done
|
||||
#5 DONE 0.0s
|
||||
|
||||
#6 [api stage-2 1/4] FROM docker.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
|
||||
#6 resolve docker.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf done
|
||||
#6 DONE 0.0s
|
||||
|
||||
#7 [api internal] load build context
|
||||
#7 transferring context: 9.92kB done
|
||||
#7 DONE 0.0s
|
||||
|
||||
#8 [api build 2/7] WORKDIR /src
|
||||
#8 CACHED
|
||||
|
||||
#9 [api build 3/7] COPY go.mod go.sum ./
|
||||
#9 CACHED
|
||||
|
||||
#10 [api build 4/7] RUN --mount=type=cache,target=/go/pkg/mod GODEBUG=http2client=0 GOPROXY="https://proxy.golang.org,direct" go mod download
|
||||
#10 CACHED
|
||||
|
||||
#11 [api build 5/7] COPY cmd/ ./cmd/
|
||||
#11 DONE 0.0s
|
||||
|
||||
#12 [api build 6/7] COPY internal/ ./internal/
|
||||
#12 DONE 0.0s
|
||||
|
||||
#13 [api build 7/7] RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server
|
||||
#13 DONE 10.9s
|
||||
|
||||
#14 [api stage-2 2/4] RUN apk add --no-cache libwebp-tools
|
||||
#14 CACHED
|
||||
|
||||
#15 [api stage-2 3/4] RUN addgroup -g 10001 app && adduser -D -u 10001 -G app app
|
||||
#15 CACHED
|
||||
|
||||
#16 [api stage-2 4/4] COPY --from=build /out/messenger /usr/local/bin/messenger
|
||||
#16 DONE 0.1s
|
||||
|
||||
#17 [api] exporting to image
|
||||
#17 exporting layers
|
||||
#17 exporting layers 0.6s done
|
||||
#17 exporting manifest sha256:d38e4cb8b5519627f629121a7d8594bcdf1d12af48551b725a9de6b1e2fa75a5
|
||||
#17 exporting manifest sha256:d38e4cb8b5519627f629121a7d8594bcdf1d12af48551b725a9de6b1e2fa75a5 done
|
||||
#17 exporting config sha256:f7008c0974492ee68462da13a3f1453ee646c42b1e5a2f1dac8553c6867b0ee2 done
|
||||
#17 exporting attestation manifest sha256:eda01449c2bd6404cf741bf9e9e8925f1985f3ac6f9d39c5398b95ab5a356bcb done
|
||||
#17 exporting manifest list sha256:cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245 done
|
||||
#17 naming to docker.io/library/mtusi-messenger:lab7 done
|
||||
#17 unpacking to docker.io/library/mtusi-messenger:lab7
|
||||
#17 unpacking to docker.io/library/mtusi-messenger:lab7 0.3s done
|
||||
#17 DONE 0.9s
|
||||
|
||||
#18 [api] resolving provenance for metadata file
|
||||
#18 DONE 0.0s
|
||||
api Built
|
||||
Container mtusi-lab7-kraykin-tempo-1 Recreate
|
||||
Container mtusi-lab7-kraykin-storage-init-1 Recreate
|
||||
Container mtusi-lab7-kraykin-broker-1 Recreate
|
||||
Container mtusi-lab7-kraykin-prometheus-1 Recreate
|
||||
Container mtusi-lab7-kraykin-collector-1 Recreate
|
||||
Container mtusi-lab7-kraykin-grafana-1 Recreate
|
||||
Container mtusi-lab7-kraykin-loki-1 Recreate
|
||||
Container mtusi-lab7-kraykin-cache-1 Recreate
|
||||
Container mtusi-lab7-kraykin-postgres-1 Recreate
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Stopping
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Stopped
|
||||
Container mtusi-lab7-kraykin-s3-1 Recreate
|
||||
Container mtusi-lab7-kraykin-storage-init-1 Recreated
|
||||
Container mtusi-lab7-kraykin-openbao-1 Recreate
|
||||
Container mtusi-lab7-kraykin-prometheus-1 Recreated
|
||||
Container mtusi-lab7-kraykin-prometheus-store-1 Recreate
|
||||
Container mtusi-lab7-kraykin-loki-1 Recreated
|
||||
Container mtusi-lab7-kraykin-loki-store-1 Recreate
|
||||
Container mtusi-lab7-kraykin-tempo-1 Recreated
|
||||
Container mtusi-lab7-kraykin-tempo-store-1 Recreate
|
||||
Container mtusi-lab7-kraykin-s3-1 Recreated
|
||||
Container mtusi-lab7-kraykin-s3-store-1 Recreate
|
||||
Container mtusi-lab7-kraykin-cache-1 Recreated
|
||||
Container mtusi-lab7-kraykin-cache-store-1 Recreate
|
||||
Container mtusi-lab7-kraykin-grafana-1 Recreated
|
||||
Container mtusi-lab7-kraykin-grafana-store-1 Recreate
|
||||
Container mtusi-lab7-kraykin-broker-1 Recreated
|
||||
Container mtusi-lab7-kraykin-broker-store-1 Recreate
|
||||
Container mtusi-lab7-kraykin-collector-1 Recreated
|
||||
Container mtusi-lab7-kraykin-collector-store-1 Recreate
|
||||
Container mtusi-lab7-kraykin-postgres-1 Recreated
|
||||
Container mtusi-lab7-kraykin-migrate-1 Recreate
|
||||
Container mtusi-lab7-kraykin-cache-store-1 Recreated
|
||||
Container mtusi-lab7-kraykin-collector-store-1 Recreated
|
||||
Container mtusi-lab7-kraykin-broker-store-1 Recreated
|
||||
Container mtusi-lab7-kraykin-migrate-1 Recreated
|
||||
Container mtusi-lab7-kraykin-prometheus-store-1 Recreated
|
||||
Container mtusi-lab7-kraykin-s3-store-1 Recreated
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Recreate
|
||||
Container mtusi-lab7-kraykin-tempo-store-1 Recreated
|
||||
Container mtusi-lab7-kraykin-loki-store-1 Recreated
|
||||
Container mtusi-lab7-kraykin-grafana-store-1 Recreated
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Recreated
|
||||
Container mtusi-lab7-kraykin-openbao-1 Recreated
|
||||
Container mtusi-lab7-kraykin-dispatcher-1 Recreate
|
||||
Container mtusi-lab7-kraykin-worker-1 Recreate
|
||||
Container mtusi-lab7-kraykin-api-2 Recreate
|
||||
Container mtusi-lab7-kraykin-api-1 Recreate
|
||||
Container mtusi-lab7-kraykin-housekeeping-1 Recreate
|
||||
Container mtusi-lab7-kraykin-housekeeping-1 Recreated
|
||||
Container mtusi-lab7-kraykin-dispatcher-1 Recreated
|
||||
Container mtusi-lab7-kraykin-api-1 Recreated
|
||||
Container mtusi-lab7-kraykin-api-2 Recreated
|
||||
Container mtusi-lab7-kraykin-lb-1 Recreate
|
||||
Container mtusi-lab7-kraykin-worker-1 Recreated
|
||||
Container mtusi-lab7-kraykin-lb-1 Recreated
|
||||
Container mtusi-lab7-kraykin-prometheus-1 Starting
|
||||
Container mtusi-lab7-kraykin-collector-1 Starting
|
||||
Container mtusi-lab7-kraykin-postgres-1 Starting
|
||||
Container mtusi-lab7-kraykin-tempo-1 Starting
|
||||
Container mtusi-lab7-kraykin-loki-1 Starting
|
||||
Container mtusi-lab7-kraykin-storage-init-1 Starting
|
||||
Container mtusi-lab7-kraykin-broker-1 Starting
|
||||
Container mtusi-lab7-kraykin-cache-1 Starting
|
||||
Container mtusi-lab7-kraykin-s3-1 Starting
|
||||
Container mtusi-lab7-kraykin-grafana-1 Starting
|
||||
Container mtusi-lab7-kraykin-tempo-1 Started
|
||||
Container mtusi-lab7-kraykin-tempo-store-1 Starting
|
||||
Container mtusi-lab7-kraykin-prometheus-1 Started
|
||||
Container mtusi-lab7-kraykin-prometheus-store-1 Starting
|
||||
Container mtusi-lab7-kraykin-broker-1 Started
|
||||
Container mtusi-lab7-kraykin-broker-store-1 Starting
|
||||
Container mtusi-lab7-kraykin-grafana-1 Started
|
||||
Container mtusi-lab7-kraykin-grafana-store-1 Starting
|
||||
Container mtusi-lab7-kraykin-prometheus-store-1 Started
|
||||
Container mtusi-lab7-kraykin-tempo-store-1 Started
|
||||
Container mtusi-lab7-kraykin-cache-1 Started
|
||||
Container mtusi-lab7-kraykin-cache-store-1 Starting
|
||||
Container mtusi-lab7-kraykin-s3-1 Started
|
||||
Container mtusi-lab7-kraykin-s3-store-1 Starting
|
||||
Container mtusi-lab7-kraykin-storage-init-1 Started
|
||||
Container mtusi-lab7-kraykin-storage-init-1 Waiting
|
||||
Container mtusi-lab7-kraykin-broker-store-1 Started
|
||||
Container mtusi-lab7-kraykin-loki-1 Started
|
||||
Container mtusi-lab7-kraykin-loki-store-1 Starting
|
||||
Container mtusi-lab7-kraykin-postgres-1 Started
|
||||
Container mtusi-lab7-kraykin-postgres-1 Waiting
|
||||
Container mtusi-lab7-kraykin-cache-store-1 Started
|
||||
Container mtusi-lab7-kraykin-grafana-store-1 Started
|
||||
Container mtusi-lab7-kraykin-collector-1 Started
|
||||
Container mtusi-lab7-kraykin-collector-store-1 Starting
|
||||
Container mtusi-lab7-kraykin-s3-store-1 Started
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Starting
|
||||
Container mtusi-lab7-kraykin-loki-store-1 Started
|
||||
Container mtusi-lab7-kraykin-collector-store-1 Started
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Started
|
||||
Container mtusi-lab7-kraykin-storage-init-1 Exited
|
||||
Container mtusi-lab7-kraykin-openbao-1 Starting
|
||||
Container mtusi-lab7-kraykin-openbao-1 Started
|
||||
Container mtusi-lab7-kraykin-postgres-1 Healthy
|
||||
Container mtusi-lab7-kraykin-migrate-1 Starting
|
||||
Container mtusi-lab7-kraykin-migrate-1 Started
|
||||
Container mtusi-lab7-kraykin-migrate-1 Waiting
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Waiting
|
||||
Container mtusi-lab7-kraykin-migrate-1 Waiting
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Waiting
|
||||
Container mtusi-lab7-kraykin-migrate-1 Waiting
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Waiting
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Waiting
|
||||
Container mtusi-lab7-kraykin-migrate-1 Waiting
|
||||
Container mtusi-lab7-kraykin-migrate-1 Exited
|
||||
Container mtusi-lab7-kraykin-migrate-1 Exited
|
||||
Container mtusi-lab7-kraykin-migrate-1 Exited
|
||||
Container mtusi-lab7-kraykin-migrate-1 Exited
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Exited
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Exited
|
||||
Container mtusi-lab7-kraykin-worker-1 Starting
|
||||
Container mtusi-lab7-kraykin-dispatcher-1 Starting
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Exited
|
||||
Container mtusi-lab7-kraykin-housekeeping-1 Starting
|
||||
Container mtusi-lab7-kraykin-s3-init-1 Exited
|
||||
Container mtusi-lab7-kraykin-api-2 Starting
|
||||
Container mtusi-lab7-kraykin-api-2 Started
|
||||
Container mtusi-lab7-kraykin-api-1 Starting
|
||||
Container mtusi-lab7-kraykin-dispatcher-1 Started
|
||||
Container mtusi-lab7-kraykin-worker-1 Started
|
||||
Container mtusi-lab7-kraykin-housekeeping-1 Started
|
||||
Container mtusi-lab7-kraykin-api-1 Started
|
||||
Container mtusi-lab7-kraykin-lb-1 Starting
|
||||
Container mtusi-lab7-kraykin-lb-1 Started
|
||||
Scoped DB grants, service certificate auth, TTL60s policies, KV and HMAC audit configured; no private output.
|
||||
HTTPS/mTLS application ready; certificate verification enabled.
|
||||
@@ -0,0 +1,285 @@
|
||||
{
|
||||
"trace_id": "812db861dd0a4b93aa8807695b66f0b2",
|
||||
"spans": [
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.pool.acquire",
|
||||
"id": "O2YRVKOYy6I=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.BEGIN",
|
||||
"id": "ibl8t1nNTiU=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.SELECT",
|
||||
"id": "MCcFjU/wpbc=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.SELECT",
|
||||
"id": "huCq7TgJ61g=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.UPDATE",
|
||||
"id": "NdsW/ZtRneo=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.UPDATE",
|
||||
"id": "KV4p5MBESl0=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.INSERT",
|
||||
"id": "aKL4ST7Emd0=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.COMMIT",
|
||||
"id": "dtxWn9Ie0X8=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "s3.request",
|
||||
"id": "u+1N60fie0E=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "image.transform",
|
||||
"id": "dtW6UvyILt8=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "s3.request",
|
||||
"id": "ljpUDpbkzKQ=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "s3.request",
|
||||
"id": "cGI9hkbOsJ8=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "s3.request",
|
||||
"id": "GlO6R2oKt0Q=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "s3.request",
|
||||
"id": "l2f55D1Pcjw=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.pool.acquire",
|
||||
"id": "z9lGAMvTtbM=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.BEGIN",
|
||||
"id": "uJcDUteTSnc=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.SELECT",
|
||||
"id": "EGnFkBgBqYw=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.UPDATE",
|
||||
"id": "Fk9IhZKRVr8=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.UPDATE",
|
||||
"id": "0/97k/31Ghg=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.INSERT",
|
||||
"id": "W82YvgGP5MA=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.COMMIT",
|
||||
"id": "zFFKbtJtSKk=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.pool.acquire",
|
||||
"id": "5YaX+CjvQr0=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "db.SELECT",
|
||||
"id": "bnzbV3PTapI=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "s3.request",
|
||||
"id": "aGQDo93CpA8=",
|
||||
"parent": "9uIhhOld4Qg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-worker",
|
||||
"name": "queue.consume",
|
||||
"id": "9uIhhOld4Qg=",
|
||||
"parent": "R5U7TxrT3zQ="
|
||||
},
|
||||
{
|
||||
"service": "messenger-dispatcher",
|
||||
"name": "queue.publish",
|
||||
"id": "R5U7TxrT3zQ=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.pool.acquire",
|
||||
"id": "35IY3FPNKUk=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.SELECT",
|
||||
"id": "+oHST1NpIO8=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.pool.acquire",
|
||||
"id": "tGuqjrSBOhw=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.SELECT",
|
||||
"id": "ouKeDW2Dq0I=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.pool.acquire",
|
||||
"id": "YYdhyluyZrw=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.INSERT",
|
||||
"id": "DiyP3QpIf7w=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.pool.acquire",
|
||||
"id": "XsCx/KIGuQw=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.BEGIN",
|
||||
"id": "UQajRvtw+3U=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.SELECT",
|
||||
"id": "yDz3YACKb1Q=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "s3.request",
|
||||
"id": "UxX7i4T/T4Y=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.INSERT",
|
||||
"id": "fMpGQNiaGSM=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.SELECT",
|
||||
"id": "JXpN2tfGZqs=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.SELECT",
|
||||
"id": "Cqz3Pg+0XM8=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.INSERT",
|
||||
"id": "qe+1wPlaTfc=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.DELETE",
|
||||
"id": "18xzGgXSD7U=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "db.COMMIT",
|
||||
"id": "u7x2LULtKYo=",
|
||||
"parent": "Yn1H6K5Bxsg="
|
||||
},
|
||||
{
|
||||
"service": "messenger-api",
|
||||
"name": "POST /chats/{id}/attachments",
|
||||
"id": "Yn1H6K5Bxsg=",
|
||||
"parent": "6EfH5YuwShc="
|
||||
}
|
||||
],
|
||||
"services": [
|
||||
"messenger-api",
|
||||
"messenger-dispatcher",
|
||||
"messenger-worker"
|
||||
],
|
||||
"log_services": [
|
||||
"messenger-api",
|
||||
"messenger-dispatcher",
|
||||
"messenger-worker"
|
||||
],
|
||||
"log_lines": 4,
|
||||
"known_synthetic_tokens_passwords_absent": true,
|
||||
"dashboard": {
|
||||
"uid": "messenger-lab7",
|
||||
"panels": 24
|
||||
},
|
||||
"actual_grafana_datasource_health": {
|
||||
"prometheus": "actual query via Grafana proxy succeeded",
|
||||
"loki": "actual query via Grafana proxy succeeded",
|
||||
"tempo": "actual query via Grafana proxy succeeded"
|
||||
},
|
||||
"network_protocol": "all queries and OTLP use verified TLS/mTLS; native loopback remains inside gateway boundary"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
PASS: real TLS trace/log/metrics chain, privacy and all three provisioned Grafana datasource connections
|
||||
@@ -0,0 +1,91 @@
|
||||
Compose can now delegate builds to bake for better performance.
|
||||
To do so, set COMPOSE_BAKE=true.
|
||||
#0 building with "desktop-linux" instance using docker driver
|
||||
|
||||
#1 [tests internal] load build definition from Dockerfile
|
||||
#1 transferring dockerfile: 1.11kB done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [tests internal] load metadata for docker.io/library/golang:1.27.4-alpine3.24
|
||||
#2 DONE 0.0s
|
||||
|
||||
#3 [tests internal] load .dockerignore
|
||||
#3 transferring context: 196B done
|
||||
#3 DONE 0.0s
|
||||
|
||||
#4 [tests internal] load build context
|
||||
#4 DONE 0.0s
|
||||
|
||||
#5 [tests build 1/7] FROM docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280
|
||||
#5 resolve docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280
|
||||
#5 resolve docker.io/library/golang:1.27.4-alpine3.24@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 4.3s done
|
||||
#5 DONE 4.3s
|
||||
|
||||
#4 [tests internal] load build context
|
||||
#4 transferring context: 3.99kB done
|
||||
#4 DONE 0.0s
|
||||
|
||||
#6 [tests build 2/7] WORKDIR /src
|
||||
#6 CACHED
|
||||
|
||||
#7 [tests build 3/7] COPY go.mod go.sum ./
|
||||
#7 CACHED
|
||||
|
||||
#8 [tests build 4/7] RUN --mount=type=cache,target=/go/pkg/mod GODEBUG=http2client=0 GOPROXY="https://proxy.golang.org,direct" go mod download
|
||||
#8 CACHED
|
||||
|
||||
#9 [tests build 5/7] COPY cmd/ ./cmd/
|
||||
#9 CACHED
|
||||
|
||||
#10 [tests build 6/7] COPY internal/ ./internal/
|
||||
#10 DONE 0.0s
|
||||
|
||||
#11 [tests build 7/7] RUN --mount=type=cache,target=/go/pkg/mod CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server
|
||||
#11 DONE 12.0s
|
||||
|
||||
#12 [tests tests 1/2] RUN apk add --no-cache gcc musl-dev libwebp-tools
|
||||
#12 1.242 ( 1/22) Installing libgcc (15.2.0-r5)
|
||||
#12 1.327 ( 2/22) Installing jansson (2.15.0-r0)
|
||||
#12 1.411 ( 3/22) Installing libstdc++ (15.2.0-r5)
|
||||
#12 1.529 ( 4/22) Installing zstd-libs (1.6.0-r1)
|
||||
#12 1.628 ( 5/22) Installing binutils (2.45.1-r1)
|
||||
#12 1.887 ( 6/22) Installing libgcc-static (15.2.0-r5)
|
||||
#12 2.036 ( 7/22) Installing libgomp (15.2.0-r5)
|
||||
#12 2.123 ( 8/22) Installing libatomic (15.2.0-r5)
|
||||
#12 2.208 ( 9/22) Installing gmp (6.3.0-r4)
|
||||
#12 2.298 (10/22) Installing isl26 (0.26-r2)
|
||||
#12 2.411 (11/22) Installing mpfr4 (4.2.2-r0)
|
||||
#12 2.508 (12/22) Installing mpc1 (1.3.1-r1)
|
||||
#12 2.593 (13/22) Installing gcc (15.2.0-r5)
|
||||
#12 5.309 (14/22) Installing giflib (5.2.2-r2)
|
||||
#12 5.391 (15/22) Installing libjpeg-turbo (3.1.3-r0)
|
||||
#12 5.484 (16/22) Installing libpng (1.6.59-r0)
|
||||
#12 5.571 (17/22) Installing libsharpyuv (1.6.0-r0)
|
||||
#12 5.652 (18/22) Installing libwebp (1.6.0-r0)
|
||||
#12 5.746 (19/22) Installing libwebpdemux (1.6.0-r0)
|
||||
#12 5.827 (20/22) Installing libwebpmux (1.6.0-r0)
|
||||
#12 5.908 (21/22) Installing libwebp-tools (1.6.0-r0)
|
||||
#12 5.994 (22/22) Installing musl-dev (1.2.6-r3)
|
||||
#12 6.215 Executing busybox-1.37.0-r31.trigger
|
||||
#12 6.219 OK: 176.0 MiB in 39 packages
|
||||
#12 DONE 6.3s
|
||||
|
||||
#13 [tests tests 2/2] RUN --mount=type=cache,target=/go/pkg/mod mkdir -p /opt/gomod && cp -a /go/pkg/mod/. /opt/gomod/
|
||||
#13 DONE 3.2s
|
||||
|
||||
#14 [tests] exporting to image
|
||||
#14 exporting layers
|
||||
#14 exporting layers 13.8s done
|
||||
#14 exporting manifest sha256:751c0994edb23c339d824f7b1b5ab34eead7fa86674f6b6a8730c0d29152b04f
|
||||
#14 exporting manifest sha256:751c0994edb23c339d824f7b1b5ab34eead7fa86674f6b6a8730c0d29152b04f done
|
||||
#14 exporting config sha256:76c5a99052717ce0a06ada850e20c70116ecfdfb4118ce3feb0f6d3eb8d8be41 0.0s done
|
||||
#14 exporting attestation manifest sha256:e9c619fec55f2e37e9c1a48c415891c9ef6a3c305fab001795e11c73366f0c74 0.0s done
|
||||
#14 exporting manifest list sha256:f6df1b400bba5b39f2293beb4bd9230788d0a240df1e278745d327d715443ebf done
|
||||
#14 naming to docker.io/library/mtusi-messenger-tests:lab7 done
|
||||
#14 unpacking to docker.io/library/mtusi-messenger-tests:lab7
|
||||
#14 unpacking to docker.io/library/mtusi-messenger-tests:lab7 3.9s done
|
||||
#14 DONE 17.8s
|
||||
|
||||
#15 [tests] resolving provenance for metadata file
|
||||
#15 DONE 0.0s
|
||||
tests Built
|
||||
@@ -0,0 +1,239 @@
|
||||
[
|
||||
{
|
||||
"target": "broker",
|
||||
"positive": {
|
||||
"ok": true
|
||||
},
|
||||
"negative": {
|
||||
"no_certificate": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"foreign_ca": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_identity_same_ca": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "collector",
|
||||
"positive": {
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
"tls": true
|
||||
},
|
||||
"negative": {
|
||||
"no_certificate": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"foreign_ca": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_identity_same_ca": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "api1",
|
||||
"positive": {
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
"tls": true
|
||||
},
|
||||
"negative": {
|
||||
"no_certificate": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"foreign_ca": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_identity_same_ca": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "api2",
|
||||
"positive": {
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
"tls": true
|
||||
},
|
||||
"negative": {
|
||||
"no_certificate": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"foreign_ca": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_identity_same_ca": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "s3",
|
||||
"positive": {
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
"tls": true
|
||||
},
|
||||
"wrong_identity": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_ca": {
|
||||
"error_category": "ca_verification_failed",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_hostname": {
|
||||
"error_category": "hostname_verification_failed",
|
||||
"ok": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "prometheus",
|
||||
"positive": {
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
"tls": true
|
||||
},
|
||||
"wrong_identity": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_ca": {
|
||||
"error_category": "ca_verification_failed",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_hostname": {
|
||||
"error_category": "hostname_verification_failed",
|
||||
"ok": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "loki",
|
||||
"positive": {
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
"tls": true
|
||||
},
|
||||
"wrong_identity": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_ca": {
|
||||
"error_category": "ca_verification_failed",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_hostname": {
|
||||
"error_category": "hostname_verification_failed",
|
||||
"ok": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "tempo",
|
||||
"positive": {
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
"tls": true
|
||||
},
|
||||
"wrong_identity": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_ca": {
|
||||
"error_category": "ca_verification_failed",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_hostname": {
|
||||
"error_category": "hostname_verification_failed",
|
||||
"ok": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "collector_metrics",
|
||||
"positive": {
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
"tls": true
|
||||
},
|
||||
"wrong_identity": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_ca": {
|
||||
"error_category": "ca_verification_failed",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_hostname": {
|
||||
"error_category": "hostname_verification_failed",
|
||||
"ok": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "ingress_metrics",
|
||||
"positive": {
|
||||
"ok": true,
|
||||
"status": 200,
|
||||
"tls": true
|
||||
},
|
||||
"wrong_identity": {
|
||||
"ok": false,
|
||||
"status": 403,
|
||||
"tls": true
|
||||
},
|
||||
"wrong_ca": {
|
||||
"error_category": "ca_verification_failed",
|
||||
"ok": false
|
||||
},
|
||||
"wrong_hostname": {
|
||||
"error_category": "hostname_verification_failed",
|
||||
"ok": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "postgres_api",
|
||||
"positive": {
|
||||
"ok": true
|
||||
},
|
||||
"wrong_ca": {
|
||||
"error_category": "ca_verification_failed",
|
||||
"ok": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "postgres_worker",
|
||||
"positive": {
|
||||
"ok": true
|
||||
},
|
||||
"wrong_ca": {
|
||||
"error_category": "ca_verification_failed",
|
||||
"ok": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"target": "cache",
|
||||
"positive": {
|
||||
"ok": true
|
||||
},
|
||||
"wrong_identity": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,103 @@
|
||||
{
|
||||
"model": "exfiltrated live worker leaf+service credentials, no host/Docker/CA compromise; operator probes use only selected worker identity; baseline is a deliberately overprivileged test fixture, never mounted into runtime worker",
|
||||
"images_before": [
|
||||
"6e202c00610daf051d71449e414f6d1a285da1a89ea49c4bb12e0528d5378ce2"
|
||||
],
|
||||
"before_least_privilege": {
|
||||
"password_table": {
|
||||
"ok": true
|
||||
},
|
||||
"bucket_administration": {
|
||||
"ok": true
|
||||
}
|
||||
},
|
||||
"accepted_while_quarantined": 8,
|
||||
"least_privilege": {
|
||||
"allowed": {
|
||||
"db_pipeline": {
|
||||
"ok": true
|
||||
},
|
||||
"s3_staging": {
|
||||
"ok": true
|
||||
},
|
||||
"queue_ping": {
|
||||
"ok": true
|
||||
}
|
||||
},
|
||||
"denied": {
|
||||
"password_table": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"sessions": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"messages": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"change_owner": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"drop_table": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"s3_private_prefix": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"s3_staging_write": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"bucket_administration": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"queue_publish": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"queue_flush": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"queue_other_key": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"bao_api_secret": {
|
||||
"ok": false,
|
||||
"error_category": "policy_denied"
|
||||
}
|
||||
}
|
||||
},
|
||||
"after_revocation": {
|
||||
"old_cert_queue": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"old_cert_s3": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"old_bao_token_denied": true,
|
||||
"old_sql_password": {
|
||||
"error_category": "credential_denied",
|
||||
"ok": false
|
||||
}
|
||||
},
|
||||
"recovery_all_ready_seconds": 4.101,
|
||||
"all_accepted_originals_identical": true,
|
||||
"background_messages_success": 98,
|
||||
"background_messages_errors": 2,
|
||||
"images_after": [
|
||||
"6e202c00610daf051d71449e414f6d1a285da1a89ea49c4bb12e0528d5378ce2"
|
||||
],
|
||||
"new_worker_connects": {
|
||||
"ok": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
{
|
||||
"model": "exfiltrated live worker leaf+service credentials, no host/Docker/CA compromise; operator probes use only selected worker identity; baseline is a deliberately overprivileged test fixture, never mounted into runtime worker",
|
||||
"images_before": [
|
||||
"cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245"
|
||||
],
|
||||
"before_least_privilege": {
|
||||
"password_table": {
|
||||
"ok": true
|
||||
},
|
||||
"bucket_administration": {
|
||||
"ok": true
|
||||
}
|
||||
},
|
||||
"accepted_while_quarantined": 8,
|
||||
"least_privilege": {
|
||||
"allowed": {
|
||||
"db_pipeline": {
|
||||
"ok": true
|
||||
},
|
||||
"db_execution_update": {
|
||||
"ok": true
|
||||
},
|
||||
"s3_staging": {
|
||||
"ok": true
|
||||
},
|
||||
"s3_final_put": {
|
||||
"ok": true
|
||||
},
|
||||
"queue_ping": {
|
||||
"ok": true
|
||||
}
|
||||
},
|
||||
"denied": {
|
||||
"password_table": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"sessions": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"messages": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"change_owner": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"change_checksum": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"drop_table": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"s3_private_prefix": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"s3_staging_write": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"s3_final_delete": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"bucket_administration": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"queue_publish": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"queue_flush": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"queue_other_key": {
|
||||
"error_category": "permission_denied",
|
||||
"ok": false
|
||||
},
|
||||
"bao_api_secret": {
|
||||
"ok": false,
|
||||
"error_category": "policy_denied"
|
||||
}
|
||||
}
|
||||
},
|
||||
"after_revocation": {
|
||||
"old_cert_queue": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"old_cert_s3": {
|
||||
"error_category": "tls_handshake_denied",
|
||||
"ok": false
|
||||
},
|
||||
"old_bao_token_denied": true,
|
||||
"old_sql_password": {
|
||||
"error_category": "credential_denied",
|
||||
"ok": false
|
||||
}
|
||||
},
|
||||
"recovery_all_ready_seconds": 3.823,
|
||||
"all_accepted_originals_identical": true,
|
||||
"background_messages_success": 80,
|
||||
"background_messages_errors": 0,
|
||||
"images_after": [
|
||||
"cb322a99165b3a55da20e45ee33ed9f55d84e6a08d932a4589bb51f9052d7245"
|
||||
],
|
||||
"new_worker_connects": {
|
||||
"ok": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
module mtusi/messenger
|
||||
|
||||
go 1.27.0
|
||||
|
||||
require (
|
||||
github.com/disintegration/imaging v1.6.2
|
||||
github.com/jackc/pgx/v5 v5.9.2
|
||||
github.com/minio/minio-go/v7 v7.0.95
|
||||
github.com/redis/go-redis/v9 v9.12.1
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0
|
||||
go.opentelemetry.io/otel v1.47.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0
|
||||
go.opentelemetry.io/otel/metric v1.47.0
|
||||
go.opentelemetry.io/otel/sdk v1.47.0
|
||||
go.opentelemetry.io/otel/sdk/log v1.47.0
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0
|
||||
go.opentelemetry.io/otel/trace v1.47.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/go-ini/ini v1.67.0 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/klauspost/compress v1.20.2 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.11 // indirect
|
||||
github.com/minio/crc64nvme v1.0.2 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/tinylib/msgp v1.3.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/log v1.47.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
|
||||
golang.org/x/image v0.45.0 // indirect
|
||||
golang.org/x/net v0.63.0 // indirect
|
||||
golang.org/x/sync v0.25.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect
|
||||
google.golang.org/grpc v1.83.2 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
)
|
||||
@@ -0,0 +1,127 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
|
||||
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
|
||||
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo=
|
||||
github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU=
|
||||
github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/minio/crc64nvme v1.0.2 h1:6uO1UxGAD+kwqWWp7mBFsi5gAse66C4NXO8cmcVculg=
|
||||
github.com/minio/crc64nvme v1.0.2/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.0.95 h1:ywOUPg+PebTMTzn9VDsoFJy32ZuARN9zhB+K3IYEvYU=
|
||||
github.com/minio/minio-go/v7 v7.0.95/go.mod h1:wOOX3uxS334vImCNRVyIDdXX9OsXDm89ToynKgqUKlo=
|
||||
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.12.1 h1:k5iquqv27aBtnTm2tIkROUDp8JBXhXZIVu1InSgvovg=
|
||||
github.com/redis/go-redis/v9 v9.12.1/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww=
|
||||
github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0 h1:/CdgE52i1OEPHhsGUqrggYNRaZy4v4YgVenGd52dRBI=
|
||||
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0/go.mod h1:9pBdbVbuehIDzxN4accnzzxEUPT8Nq7grbZMo+J1VN4=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 h1:5WVp40k2fJHuc5BtNTgKk+EugKFT8Eg3lywFfCPI/nE=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0/go.mod h1:59nH0RYCGHRlwt15WyioeSYINBbuObeBpTowPhEKWHY=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0 h1:7kszRN4Ze5GeAkUnBjBSUIunVBMA+mZIG04auueqguM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0/go.mod h1:CLzakYy8jOdkBfcveCWYkeKJxujcF4xPhh2Z7IfE98U=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
|
||||
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
|
||||
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
|
||||
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
|
||||
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
|
||||
go.opentelemetry.io/otel/metric/x v0.69.0 h1:DjRLr15H83v+hCW7JA9NoJvOkYTtmq5YoDRbe9deYpM=
|
||||
go.opentelemetry.io/otel/metric/x v0.69.0/go.mod h1:uVvsMPMFFyj/HUQfrUnH3JjnOQ1dwFDorgFLRBasM0k=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
|
||||
go.opentelemetry.io/otel/sdk/log v1.47.0 h1:W4N/ZfgpkRRnmARnqYoQ6BrWA0mrj8IzVDNLlpmUJZY=
|
||||
go.opentelemetry.io/otel/sdk/log v1.47.0/go.mod h1:Wu74Z2EmOKXi2FleSNAb0Hyau2G+r5kubSEMJw5aAMs=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.23.0 h1:j3pm42QCrKYYLLkI6OrV1QHFkUfDA6/4EP+Y1PzggLg=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.23.0/go.mod h1:zt0gEnuTZgDvqvczHwYswz93eqMaIr6upTTsdV/HUlU=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
|
||||
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
|
||||
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
|
||||
golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
|
||||
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
||||
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc h1:rZHRz0ogq4Pid1IKtA/ivHi8XONVF5tqUQXA2TtgpkE=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:K/n0XLazCJHjD73YuMyNJsN38BPPy1kfFnKxUXaThFU=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Grafana provisioning accepts PEM values, not file paths; keep only in memory.
|
||||
export TLS_CA_CONTENT="$(cat /run/tls/ca.crt)"
|
||||
export TLS_CERT_CONTENT="$(cat /run/tls/cert.crt)"
|
||||
export TLS_KEY_CONTENT="$(cat /run/tls/key.key)"
|
||||
exec /run.sh
|
||||
@@ -0,0 +1,697 @@
|
||||
{
|
||||
"uid": "messenger-lab7",
|
||||
"title": "Messenger: API and image pipeline",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"refresh": "5s",
|
||||
"time": {
|
||||
"from": "now-15m",
|
||||
"to": "now"
|
||||
},
|
||||
"tags": [
|
||||
"highload",
|
||||
"lab6"
|
||||
],
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "API successful / error RPS (business only)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (status_class) (rate(http_server_requests_total{route!~\"/health.*\"}[30s]))",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "API 5xx ratio",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "(sum(rate(http_server_requests_total{route!~\"/health.*\",status_class=\"5xx\"}[30s])) or vector(0)) / clamp_min(sum(rate(http_server_requests_total{route!~\"/health.*\"}[30s])),0.001)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "API p50 across replicas (histogram)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.5,sum by(le)(rate(http_server_duration_seconds_bucket{route!~\"/health.*\"}[60s])))",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "API p95 across replicas (histogram)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95,sum by(le)(rate(http_server_duration_seconds_bucket{route!~\"/health.*\"}[60s])))",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "API p99 across replicas (histogram)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.99,sum by(le)(rate(http_server_duration_seconds_bucket{route!~\"/health.*\"}[60s])))",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Worker attempt outcomes / second",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by(outcome)(rate(messenger_jobs_total[60s]))",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "Worker processing p95",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(.95,sum by(le)(rate(messenger_job_duration_seconds_bucket[60s])))",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "Time to ready p95 (completed)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(.95,sum by(le)(rate(messenger_attachment_ready_duration_seconds_bucket[60s])))",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "Outstanding jobs (DB authority, includes processing)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max(messenger_queue_depth)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"title": "Oldest unfinished age",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max(messenger_queue_oldest_age_seconds)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"title": "Worker saturation busy / capacity",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 40,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(messenger_worker_busy)/clamp_min(sum(messenger_worker_capacity),1)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"title": "DB acquired / max",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 40,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger_db_pool_used / messenger_db_pool_limit",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"title": "DB pool empty acquire events / second",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 48,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "rate(messenger_db_pool_waits_total[60s])",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"title": "Process RSS (parent, excludes transform child)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 48,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "process_memory_usage_bytes",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"title": "Process CPU cores (parent, excludes transform child)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 56,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "rate(process_cpu_time_seconds_total[60s])",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"title": "Ready SLI bad ratio 10m, includes unfinished >5s",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 56,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(increase(messenger_attachment_sli_bad_total[10m])) / clamp_min(sum(increase(messenger_attachment_sli_total[10m])),1)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"title": "Ingress API availability SLI 10m (includes LB 503)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 64,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "1-(sum(increase(haproxy_backend_http_responses_total{proxy=\"replicas\",code=\"5xx\"}[10m])) or vector(0))/clamp_min(sum(increase(haproxy_backend_http_responses_total{proxy=\"replicas\"}[10m])),1)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"title": "Collector dropped spans (counter)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 64,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(otelcol_exporter_send_failed_spans_total)",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"title": "API structured logs",
|
||||
"type": "logs",
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 72,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "{service_name=\"messenger-api\"}",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"title": "Worker structured logs",
|
||||
"type": "logs",
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 72,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "{service_name=\"messenger-worker\"}",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"title": "Firing alerts",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 80,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "ALERTS{alertstate=\"firing\"}",
|
||||
"legendFormat": "{{service_name}} {{outcome}} {{quantile}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 22,
|
||||
"title": "Container RAM including transform children",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 80,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "container_memory_usage_bytes",
|
||||
"legendFormat": "{{service_name}} {{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 23,
|
||||
"title": "Container CPU cores including transform children",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 88,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "rate(container_cpu_time_seconds_total[60s])",
|
||||
"legendFormat": "{{service_name}} {{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 24,
|
||||
"title": "DB pending acquire calls (current)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 88,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger_db_pool_waiting",
|
||||
"legendFormat": "{{service_name}} {{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": [
|
||||
{
|
||||
"title": "Tempo traces",
|
||||
"type": "link",
|
||||
"url": "/explore?left=%7B%22datasource%22:%22tempo%22%7D",
|
||||
"targetBlank": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: Messenger
|
||||
folder: Highload labs
|
||||
type: file
|
||||
options: {path: /var/lib/grafana/dashboards}
|
||||
@@ -0,0 +1,40 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: https://prometheus:9090
|
||||
isDefault: true
|
||||
jsonData: {tlsAuth: true, tlsAuthWithCACert: true, httpMethod: GET}
|
||||
secureJsonData: {tlsCACert: '${TLS_CA_CONTENT}', tlsClientCert: '${TLS_CERT_CONTENT}', tlsClientKey: '${TLS_KEY_CONTENT}'}
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: https://loki:3100
|
||||
secureJsonData: {tlsCACert: '${TLS_CA_CONTENT}', tlsClientCert: '${TLS_CERT_CONTENT}', tlsClientKey: '${TLS_KEY_CONTENT}'}
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherRegex: trace_id
|
||||
matcherType: label
|
||||
datasourceUid: tempo
|
||||
url: '$${__value.raw}'
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: https://tempo:3200
|
||||
secureJsonData: {tlsCACert: '${TLS_CA_CONTENT}', tlsClientCert: '${TLS_CERT_CONTENT}', tlsClientKey: '${TLS_KEY_CONTENT}'}
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: '-1m'
|
||||
spanEndTimeShift: '1m'
|
||||
filterByTraceID: true
|
||||
filterBySpanID: false
|
||||
@@ -0,0 +1,41 @@
|
||||
global
|
||||
maxconn 512
|
||||
log stdout format raw local0
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||
defaults
|
||||
log global
|
||||
mode http
|
||||
timeout connect 800ms
|
||||
timeout client 35s
|
||||
timeout server 35s
|
||||
timeout check 1500ms
|
||||
retries 0
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 2
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 1s
|
||||
hold obsolete 1s
|
||||
frontend public
|
||||
bind :8443 ssl crt /run/tls/full.pem
|
||||
http-response set-header Strict-Transport-Security max-age=86400
|
||||
use_backend readiness if { path_beg /health/ }
|
||||
default_backend replicas
|
||||
backend replicas
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
default-server inter 1s fall 2 rise 1
|
||||
server-template api 4 api:8080 ssl verify required ca-file /run/tls/ca.crt crt /run/tls/full.pem sni str(api) verifyhost api check resolvers docker init-addr libc,none resolve-prefer ipv4
|
||||
backend readiness
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
default-server inter 1s fall 2 rise 1
|
||||
server-template api 4 api:8080 ssl verify required ca-file /run/tls/ca.crt crt /run/tls/full.pem sni str(api) verifyhost api check resolvers docker init-addr libc,none resolve-prefer ipv4
|
||||
frontend metrics
|
||||
bind :8404 ssl crt /run/tls/full.pem ca-file /run/tls/ca.crt verify required
|
||||
http-request deny unless { ssl_c_s_dn(CN) -m str prometheus }
|
||||
http-request use-service prometheus-exporter if { path /metrics }
|
||||
@@ -0,0 +1,29 @@
|
||||
auth_enabled: false
|
||||
server: {http_listen_address: 127.0.0.1, http_listen_port: 3101, grpc_listen_address: 127.0.0.1}
|
||||
common:
|
||||
instance_addr: 127.0.0.1
|
||||
path_prefix: /loki
|
||||
storage:
|
||||
filesystem: {chunks_directory: /loki/chunks, rules_directory: /loki/rules}
|
||||
replication_factor: 1
|
||||
ring: {kvstore: {store: inmemory}}
|
||||
schema_config:
|
||||
configs:
|
||||
- from: '2024-01-01'
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index: {prefix: index_, period: 24h}
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
retention_period: 24h
|
||||
otlp_config:
|
||||
resource_attributes:
|
||||
attributes_config:
|
||||
- action: structured_metadata
|
||||
attributes: [service.instance.id]
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
analytics: {reporting_enabled: false}
|
||||
@@ -0,0 +1,3 @@
|
||||
path "kv/data/api" { capabilities = ["read"] }
|
||||
path "auth/token/lookup-self" { capabilities = ["read"] }
|
||||
path "auth/token/revoke-self" { capabilities = ["update"] }
|
||||
@@ -0,0 +1,3 @@
|
||||
path "kv/data/dispatcher" { capabilities = ["read"] }
|
||||
path "auth/token/lookup-self" { capabilities = ["read"] }
|
||||
path "auth/token/revoke-self" { capabilities = ["update"] }
|
||||
@@ -0,0 +1,3 @@
|
||||
path "kv/data/housekeeping" { capabilities = ["read"] }
|
||||
path "auth/token/lookup-self" { capabilities = ["read"] }
|
||||
path "auth/token/revoke-self" { capabilities = ["update"] }
|
||||
@@ -0,0 +1,3 @@
|
||||
path "kv/data/worker" { capabilities = ["read"] }
|
||||
path "auth/token/lookup-self" { capabilities = ["read"] }
|
||||
path "auth/token/revoke-self" { capabilities = ["update"] }
|
||||
@@ -0,0 +1,21 @@
|
||||
ui = false
|
||||
api_addr = "https://openbao:8200"
|
||||
cluster_addr = "https://openbao:8201"
|
||||
storage "raft" {
|
||||
path = "/bao/data/raft-v2"
|
||||
node_id = "lab7"
|
||||
performance_multiplier = 1
|
||||
}
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
tls_cert_file = "/run/tls/cert.crt"
|
||||
tls_key_file = "/run/tls/key.key"
|
||||
tls_client_ca_file = "/run/tls/ca.crt"
|
||||
tls_min_version = "tls12"
|
||||
}
|
||||
default_lease_ttl = "60s"
|
||||
max_lease_ttl = "120s"
|
||||
audit "file" "file" {
|
||||
description = "Operator-owned persistent HMAC audit"
|
||||
options { file_path = "/bao/audit/audit.json" }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http: {endpoint: '127.0.0.1:4319'}
|
||||
processors:
|
||||
memory_limiter: {check_interval: 1s, limit_mib: 180, spike_limit_mib: 40}
|
||||
batch: {timeout: 1s, send_batch_size: 128, send_batch_max_size: 256}
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: '127.0.0.1:8891'
|
||||
resource_to_telemetry_conversion: {enabled: true}
|
||||
otlphttp/tempo:
|
||||
endpoint: https://tempo:4318
|
||||
tls: {ca_file: /run/tls/ca.crt, cert_file: /run/tls/cert.crt, key_file: /run/tls/key.key}
|
||||
timeout: 2s
|
||||
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 5s, max_elapsed_time: 15s}
|
||||
sending_queue: {enabled: true, num_consumers: 2, queue_size: 64}
|
||||
otlphttp/loki:
|
||||
endpoint: https://loki:3100/otlp
|
||||
tls: {ca_file: /run/tls/ca.crt, cert_file: /run/tls/cert.crt, key_file: /run/tls/key.key}
|
||||
timeout: 2s
|
||||
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 5s, max_elapsed_time: 15s}
|
||||
sending_queue: {enabled: true, num_consumers: 2, queue_size: 64}
|
||||
service:
|
||||
telemetry:
|
||||
metrics:
|
||||
level: detailed
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus: {host: 127.0.0.1, port: 8890}
|
||||
pipelines:
|
||||
traces: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/tempo]}
|
||||
metrics: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [prometheus]}
|
||||
logs: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/loki]}
|
||||
@@ -0,0 +1,3 @@
|
||||
local all all trust
|
||||
hostnossl all all all reject
|
||||
hostssl messenger all all scram-sha-256
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
mkdir -p /tmp/pg-tls
|
||||
cp /run/tls/cert.crt /tmp/pg-tls/cert.crt
|
||||
cp /run/tls/key.key /tmp/pg-tls/key.key
|
||||
chown -R postgres:postgres /tmp/pg-tls
|
||||
chmod 600 /tmp/pg-tls/key.key
|
||||
exec /usr/local/bin/docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/tmp/pg-tls/cert.crt -c ssl_key_file=/tmp/pg-tls/key.key -c hba_file=/config/pg_hba.conf -c password_encryption=scram-sha-256
|
||||
@@ -0,0 +1,29 @@
|
||||
groups:
|
||||
- name: messenger
|
||||
interval: 2s
|
||||
rules:
|
||||
- alert: APIHighErrorRate
|
||||
expr: (sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[30s])) or vector(0)) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[30s])), 0.001) > 0.1
|
||||
for: 6s
|
||||
labels: {severity: warning}
|
||||
annotations: {summary: 'API 5xx above 10% for 30s window', runbook: 'RUNBOOK.md#db'}
|
||||
- alert: QueueLag
|
||||
expr: max(messenger_queue_oldest_age_seconds) > 5 and max(messenger_queue_depth) > 0
|
||||
for: 6s
|
||||
labels: {severity: warning}
|
||||
annotations: {summary: 'Oldest unfinished job exceeds 5s', runbook: 'RUNBOOK.md#worker'}
|
||||
- alert: APIBudgetFastBurn
|
||||
expr: ((sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[10s])) or vector(0)) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[10s])),0.001) > 6 * 0.01) and ((sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[60s])) or vector(0)) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[60s])),0.001) > 6 * 0.01)
|
||||
for: 10s
|
||||
labels: {severity: critical, slo: api_99}
|
||||
annotations: {summary: 'API budget burn >6x in 10s and 60s', runbook: 'RUNBOOK.md#db'}
|
||||
- alert: APIBudgetSlowBurn
|
||||
expr: ((sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[30s])) or vector(0)) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[30s])),0.001) > 2 * 0.01) and ((sum(rate(haproxy_backend_http_responses_total{proxy="replicas",code="5xx"}[120s])) or vector(0)) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="replicas"}[120s])),0.001) > 2 * 0.01)
|
||||
for: 20s
|
||||
labels: {severity: warning, slo: api_99}
|
||||
annotations: {summary: 'API budget burn >2x in 30s and 120s', runbook: 'RUNBOOK.md#db'}
|
||||
- alert: ReadyBudgetFastBurn
|
||||
expr: (sum(rate(messenger_attachment_sli_bad_total[10s])) / clamp_min(sum(rate(messenger_attachment_sli_total[10s])),0.001) > 6 * 0.05) and (sum(rate(messenger_attachment_sli_bad_total[60s])) / clamp_min(sum(rate(messenger_attachment_sli_total[60s])),0.001) > 6 * 0.05)
|
||||
for: 10s
|
||||
labels: {severity: critical, slo: ready_95}
|
||||
annotations: {summary: 'Ready deadline budget burn >6x in 10s and 60s', runbook: 'RUNBOOK.md#worker'}
|
||||
@@ -0,0 +1,15 @@
|
||||
global: {scrape_interval: 2s, evaluation_interval: 2s}
|
||||
rule_files: [/etc/prometheus/alerts.yaml]
|
||||
scrape_configs:
|
||||
- job_name: messenger
|
||||
scheme: https
|
||||
tls_config: {ca_file: /run/tls/ca.crt, cert_file: /run/tls/cert.crt, key_file: /run/tls/key.key}
|
||||
static_configs: [{targets: ['collector:8889']}]
|
||||
- job_name: collector
|
||||
scheme: https
|
||||
tls_config: {ca_file: /run/tls/ca.crt, cert_file: /run/tls/cert.crt, key_file: /run/tls/key.key}
|
||||
static_configs: [{targets: ['collector:8888']}]
|
||||
- job_name: ingress
|
||||
scheme: https
|
||||
tls_config: {ca_file: /run/tls/ca.crt, cert_file: /run/tls/cert.crt, key_file: /run/tls/key.key}
|
||||
static_configs: [{targets: ['lb:8404']}]
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject",
|
||||
"s3:DeleteObject"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::messenger-attachments/staging/*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetObject"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::messenger-attachments/originals/*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetObject",
|
||||
"s3:DeleteObject"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::messenger-attachments/staging/*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::messenger-attachments"
|
||||
],
|
||||
"Condition": {
|
||||
"StringLike": {
|
||||
"s3:prefix": [
|
||||
"staging/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
. /run/operator/users.sh
|
||||
until mc alias set local http://127.0.0.1:9001 "$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null 2>&1; do sleep 1; done
|
||||
mc mb --ignore-existing local/messenger-attachments >/dev/null
|
||||
mc anonymous set none local/messenger-attachments >/dev/null
|
||||
for role in api worker housekeeping; do
|
||||
mc admin policy create local "lab7-$role" "/config/$role.json" >/dev/null
|
||||
case "$role" in
|
||||
api) access=$API_S3_ACCESS_KEY_ID; secret=$API_S3_SECRET_ACCESS_KEY;;
|
||||
worker) access=$WORKER_S3_ACCESS_KEY_ID; secret=$WORKER_S3_SECRET_ACCESS_KEY;;
|
||||
housekeeping) access=$HOUSEKEEPING_S3_ACCESS_KEY_ID; secret=$HOUSEKEEPING_S3_SECRET_ACCESS_KEY;;
|
||||
esac
|
||||
mc admin user add local "$access" "$secret" >/dev/null
|
||||
mc admin policy attach local "lab7-$role" --user "$access" >/dev/null
|
||||
done
|
||||
printf '%s\n' 'Private bucket with separate prefix-scoped identities ready'
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetObject"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::messenger-attachments/staging/*",
|
||||
"arn:aws:s3:::messenger-attachments/originals/*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:PutObject"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::messenger-attachments/originals/*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
server: {http_listen_address: 127.0.0.1, http_listen_port: 3201, grpc_listen_address: 127.0.0.1}
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http: {endpoint: '127.0.0.1:4319'}
|
||||
ingester:
|
||||
trace_idle_period: 2s
|
||||
max_block_duration: 5m
|
||||
compactor:
|
||||
compaction: {block_retention: 24h}
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
local: {path: /var/tempo/blocks}
|
||||
wal: {path: /var/tempo/wal}
|
||||
usage_report: {reporting_enabled: false}
|
||||
@@ -0,0 +1,12 @@
|
||||
[
|
||||
{
|
||||
"listen": ":6379",
|
||||
"target": "127.0.0.1:6380",
|
||||
"identities": [
|
||||
"worker",
|
||||
"dispatcher",
|
||||
"operator"
|
||||
],
|
||||
"raw": true
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,11 @@
|
||||
[
|
||||
{
|
||||
"listen": ":6379",
|
||||
"target": "127.0.0.1:6380",
|
||||
"identities": [
|
||||
"api",
|
||||
"operator"
|
||||
],
|
||||
"raw": true
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,122 @@
|
||||
[
|
||||
{
|
||||
"listen": ":4318",
|
||||
"target": "127.0.0.1:4319",
|
||||
"identities": [
|
||||
"api",
|
||||
"worker",
|
||||
"dispatcher",
|
||||
"housekeeping"
|
||||
],
|
||||
"rules": [
|
||||
{
|
||||
"identity": "api",
|
||||
"methods": [
|
||||
"POST"
|
||||
],
|
||||
"prefixes": [
|
||||
"/v1/traces",
|
||||
"/v1/logs",
|
||||
"/v1/metrics"
|
||||
]
|
||||
},
|
||||
{
|
||||
"identity": "worker",
|
||||
"methods": [
|
||||
"POST"
|
||||
],
|
||||
"prefixes": [
|
||||
"/v1/traces",
|
||||
"/v1/logs",
|
||||
"/v1/metrics"
|
||||
]
|
||||
},
|
||||
{
|
||||
"identity": "dispatcher",
|
||||
"methods": [
|
||||
"POST"
|
||||
],
|
||||
"prefixes": [
|
||||
"/v1/traces",
|
||||
"/v1/logs",
|
||||
"/v1/metrics"
|
||||
]
|
||||
},
|
||||
{
|
||||
"identity": "housekeeping",
|
||||
"methods": [
|
||||
"POST"
|
||||
],
|
||||
"prefixes": [
|
||||
"/v1/traces",
|
||||
"/v1/logs",
|
||||
"/v1/metrics"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"listen": ":8889",
|
||||
"target": "127.0.0.1:8891",
|
||||
"identities": [
|
||||
"prometheus",
|
||||
"operator"
|
||||
],
|
||||
"rules": [
|
||||
{
|
||||
"identity": "prometheus",
|
||||
"methods": [
|
||||
"GET"
|
||||
],
|
||||
"prefixes": [
|
||||
"/metrics"
|
||||
]
|
||||
},
|
||||
{
|
||||
"identity": "operator",
|
||||
"methods": [
|
||||
"GET",
|
||||
"POST",
|
||||
"PUT",
|
||||
"DELETE",
|
||||
"HEAD"
|
||||
],
|
||||
"prefixes": [
|
||||
"/"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"listen": ":8888",
|
||||
"target": "127.0.0.1:8890",
|
||||
"identities": [
|
||||
"prometheus",
|
||||
"operator"
|
||||
],
|
||||
"rules": [
|
||||
{
|
||||
"identity": "prometheus",
|
||||
"methods": [
|
||||
"GET"
|
||||
],
|
||||
"prefixes": [
|
||||
"/metrics"
|
||||
]
|
||||
},
|
||||
{
|
||||
"identity": "operator",
|
||||
"methods": [
|
||||
"GET",
|
||||
"POST",
|
||||
"PUT",
|
||||
"DELETE",
|
||||
"HEAD"
|
||||
],
|
||||
"prefixes": [
|
||||
"/"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,7 @@
|
||||
[
|
||||
{
|
||||
"listen": ":3000",
|
||||
"target": "127.0.0.1:3001",
|
||||
"identities": []
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,48 @@
|
||||
[
|
||||
{
|
||||
"listen": ":3100",
|
||||
"target": "127.0.0.1:3101",
|
||||
"identities": [
|
||||
"collector",
|
||||
"grafana",
|
||||
"operator"
|
||||
],
|
||||
"rules": [
|
||||
{
|
||||
"identity": "collector",
|
||||
"methods": [
|
||||
"POST"
|
||||
],
|
||||
"prefixes": [
|
||||
"/otlp/v1/logs"
|
||||
]
|
||||
},
|
||||
{
|
||||
"identity": "grafana",
|
||||
"methods": [
|
||||
"GET"
|
||||
],
|
||||
"prefixes": [
|
||||
"/loki/api/v1/query",
|
||||
"/loki/api/v1/label",
|
||||
"/loki/api/v1/series",
|
||||
"/loki/api/v1/index",
|
||||
"/loki/api/v1/status/buildinfo"
|
||||
]
|
||||
},
|
||||
{
|
||||
"identity": "operator",
|
||||
"methods": [
|
||||
"GET",
|
||||
"POST",
|
||||
"PUT",
|
||||
"DELETE",
|
||||
"HEAD"
|
||||
],
|
||||
"prefixes": [
|
||||
"/"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,39 @@
|
||||
[
|
||||
{
|
||||
"listen": ":9090",
|
||||
"target": "127.0.0.1:9091",
|
||||
"identities": [
|
||||
"grafana",
|
||||
"operator"
|
||||
],
|
||||
"rules": [
|
||||
{
|
||||
"identity": "grafana",
|
||||
"methods": [
|
||||
"GET",
|
||||
"POST"
|
||||
],
|
||||
"prefixes": [
|
||||
"/api/v1/query",
|
||||
"/api/v1/label",
|
||||
"/api/v1/series",
|
||||
"/api/v1/metadata",
|
||||
"/api/v1/status/buildinfo"
|
||||
]
|
||||
},
|
||||
{
|
||||
"identity": "operator",
|
||||
"methods": [
|
||||
"GET",
|
||||
"POST",
|
||||
"PUT",
|
||||
"DELETE",
|
||||
"HEAD"
|
||||
],
|
||||
"prefixes": [
|
||||
"/"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,12 @@
|
||||
[
|
||||
{
|
||||
"listen": ":9000",
|
||||
"target": "127.0.0.1:9001",
|
||||
"identities": [
|
||||
"api",
|
||||
"worker",
|
||||
"housekeeping",
|
||||
"operator"
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,53 @@
|
||||
[
|
||||
{
|
||||
"listen": ":3200",
|
||||
"target": "127.0.0.1:3201",
|
||||
"identities": [
|
||||
"grafana",
|
||||
"operator"
|
||||
],
|
||||
"rules": [
|
||||
{
|
||||
"identity": "grafana",
|
||||
"methods": [
|
||||
"GET"
|
||||
],
|
||||
"prefixes": [
|
||||
"/api/",
|
||||
"/ready"
|
||||
]
|
||||
},
|
||||
{
|
||||
"identity": "operator",
|
||||
"methods": [
|
||||
"GET",
|
||||
"POST",
|
||||
"PUT",
|
||||
"DELETE",
|
||||
"HEAD"
|
||||
],
|
||||
"prefixes": [
|
||||
"/"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"listen": ":4318",
|
||||
"target": "127.0.0.1:4319",
|
||||
"identities": [
|
||||
"collector"
|
||||
],
|
||||
"rules": [
|
||||
{
|
||||
"identity": "collector",
|
||||
"methods": [
|
||||
"POST"
|
||||
],
|
||||
"prefixes": [
|
||||
"/v1/traces"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,108 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"embed"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"mtusi/messenger/internal/telemetry"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrations embed.FS
|
||||
|
||||
func Open(ctx context.Context, url string) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid database configuration")
|
||||
}
|
||||
if cfg.ConnConfig.TLSConfig == nil || cfg.ConnConfig.TLSConfig.InsecureSkipVerify || cfg.ConnConfig.TLSConfig.ServerName == "" || len(cfg.ConnConfig.Fallbacks) != 0 {
|
||||
return nil, fmt.Errorf("database requires verified TLS without fallback")
|
||||
}
|
||||
cfg.MaxConns = 10
|
||||
if v := os.Getenv("DB_POOL_MAX"); v != "" {
|
||||
n, e := strconv.Atoi(v)
|
||||
if e != nil || n < 1 || n > 64 {
|
||||
return nil, fmt.Errorf("DB_POOL_MAX must be 1..64")
|
||||
}
|
||||
cfg.MaxConns = int32(n)
|
||||
}
|
||||
cfg.ConnConfig.Tracer = telemetry.DBTracer{}
|
||||
cfg.MinConns = 0
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.ConnConfig.ConnectTimeout = 2 * time.Second
|
||||
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "2000"
|
||||
cfg.ConnConfig.RuntimeParams["lock_timeout"] = "1000"
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot create database pool")
|
||||
}
|
||||
if err = pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("database unavailable")
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// All migrations and the version ledger commit together. An advisory lock also
|
||||
// serializes bootstrap across API instances; edited applied migrations fail.
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(2026002)"); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())`); err != nil {
|
||||
return err
|
||||
}
|
||||
entries, err := migrations.ReadDir("migrations")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
|
||||
for _, entry := range entries {
|
||||
body, err := migrations.ReadFile("migrations/" + entry.Name())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
checksum := fmt.Sprintf("%x", sha256.Sum256(body))
|
||||
var stored string
|
||||
rows, err := tx.Query(ctx, "SELECT checksum FROM schema_migrations WHERE version=$1", entry.Name())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
found := rows.Next()
|
||||
if found {
|
||||
err = rows.Scan(&stored)
|
||||
}
|
||||
if err == nil {
|
||||
err = rows.Err()
|
||||
}
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found {
|
||||
if stored != checksum {
|
||||
return fmt.Errorf("applied migration changed: %s", entry.Name())
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err = tx.Exec(ctx, string(body)); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version,checksum) VALUES($1,$2)", entry.Name(), checksum); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
last_message_at timestamptz NOT NULL DEFAULT '-infinity'
|
||||
);
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX chat_members_user_idx ON chat_members(user_id, chat_id);
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz NOT NULL,
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX messages_history_idx ON messages(chat_id, created_at, id);
|
||||
CREATE INDEX chats_order_idx ON chats(created_at, id);
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE INDEX sessions_expiry_idx ON sessions(expires_at);
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE message_requests (
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
key text NOT NULL,
|
||||
body_hash bytea NOT NULL,
|
||||
response jsonb NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
PRIMARY KEY(user_id,chat_id,key)
|
||||
);
|
||||
CREATE INDEX message_requests_expiry_idx ON message_requests(expires_at);
|
||||
@@ -0,0 +1,29 @@
|
||||
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
|
||||
ALTER TABLE messages ADD CHECK(char_length(text) BETWEEN 0 AND 4000);
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
owner_id uuid NOT NULL REFERENCES users(id),
|
||||
filename text NOT NULL,
|
||||
object_key text NOT NULL UNIQUE,
|
||||
content_type text NOT NULL CHECK(content_type IN ('image/png','image/jpeg')),
|
||||
size_bytes bigint NOT NULL CHECK(size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 text NOT NULL CHECK(sha256 ~ '^[a-f0-9]{64}$'),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages(id),
|
||||
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||
position integer NOT NULL CHECK(position BETWEEN 0 AND 9),
|
||||
PRIMARY KEY(message_id,attachment_id),
|
||||
UNIQUE(message_id,position)
|
||||
);
|
||||
-- Durable upload journal is committed BEFORE PUT, so incomplete work remains
|
||||
-- attributable after process termination. Final metadata + journal deletion
|
||||
-- share one PG transaction, under the same per-key lock as the reconciler.
|
||||
CREATE TABLE upload_intents (
|
||||
object_key text PRIMARY KEY,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE INDEX attachments_chat_idx ON attachments(chat_id);
|
||||
@@ -0,0 +1,30 @@
|
||||
ALTER TABLE attachments ADD COLUMN status text NOT NULL DEFAULT 'ready' CHECK(status IN ('queued','processing','ready','failed'));
|
||||
ALTER TABLE attachments ADD COLUMN error_code text;
|
||||
ALTER TABLE attachments ADD COLUMN variants jsonb NOT NULL DEFAULT '[]';
|
||||
ALTER TABLE attachments ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1 CHECK(pipeline_version>0);
|
||||
ALTER TABLE attachments ADD COLUMN staging_key text;
|
||||
CREATE TABLE pipeline_jobs (
|
||||
job_id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||
pipeline_version integer NOT NULL CHECK(pipeline_version>0),
|
||||
attempt integer NOT NULL DEFAULT 0,
|
||||
lease_token uuid,
|
||||
lease_until timestamptz,
|
||||
next_attempt_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
published_at timestamptz,
|
||||
finished_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
traceparent text NOT NULL DEFAULT '',
|
||||
tracestate text NOT NULL DEFAULT '',
|
||||
UNIQUE(attachment_id,pipeline_version)
|
||||
);
|
||||
CREATE INDEX pipeline_dispatch_idx ON pipeline_jobs(next_attempt_at) WHERE finished_at IS NULL;
|
||||
CREATE TABLE pipeline_audit (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES pipeline_jobs(job_id),
|
||||
event text NOT NULL,
|
||||
attempt integer NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
-- This is the durable, queryable failed registry (DLQ equivalent).
|
||||
CREATE VIEW failed_jobs AS SELECT j.job_id,j.attachment_id,j.pipeline_version,j.attempt,a.error_code,j.finished_at FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id AND a.pipeline_version=j.pipeline_version WHERE a.status='failed';
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE pipeline_jobs ADD COLUMN ready_at timestamptz;
|
||||
CREATE INDEX pipeline_jobs_created_idx ON pipeline_jobs(created_at);
|
||||
@@ -0,0 +1,12 @@
|
||||
CREATE TABLE auth_limits (bucket text NOT NULL, window_id bigint NOT NULL, count integer NOT NULL, PRIMARY KEY(bucket,window_id));
|
||||
-- Both counters increment in one transaction, global key locked first.
|
||||
CREATE FUNCTION auth_admit(subject text) RETURNS boolean LANGUAGE plpgsql AS $$
|
||||
DECLARE win bigint; total integer; per_subject integer;
|
||||
BEGIN
|
||||
win := floor(extract(epoch from clock_timestamp()) / 60);
|
||||
INSERT INTO auth_limits VALUES ('global',win,1) ON CONFLICT(bucket,window_id) DO UPDATE SET count=auth_limits.count+1 RETURNING count INTO total;
|
||||
IF total>120 THEN RETURN false; END IF;
|
||||
INSERT INTO auth_limits VALUES (subject,win,1) ON CONFLICT(bucket,window_id) DO UPDATE SET count=auth_limits.count+1 RETURNING count INTO per_subject;
|
||||
DELETE FROM auth_limits WHERE window_id<win-1;
|
||||
RETURN per_subject<=12;
|
||||
END $$;
|
||||
@@ -0,0 +1,331 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"mime"
|
||||
"mtusi/messenger/internal/security"
|
||||
"mtusi/messenger/internal/telemetry"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"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 maxUpload = 10 << 20
|
||||
const maxPixels = 40000000
|
||||
|
||||
type ObjectStore struct {
|
||||
Client *minio.Client
|
||||
Bucket string
|
||||
HealthURL string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
func NewObjectStore(endpoint, bucket, access, secret string) (*ObjectStore, error) {
|
||||
u, e := url.Parse(endpoint)
|
||||
if e != nil || u.Host == "" || u.Scheme != "https" {
|
||||
return nil, fmt.Errorf("invalid S3 endpoint")
|
||||
}
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
tc, e := security.ClientTLS()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
transport.TLSClientConfig = tc
|
||||
transport.MaxConnsPerHost = 8
|
||||
transport.ResponseHeaderTimeout = 5 * time.Second
|
||||
client, e := minio.New(u.Host, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: u.Scheme == "https", Region: "us-east-1", Transport: telemetry.Transport(transport), MaxRetries: 1})
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("invalid S3 configuration")
|
||||
}
|
||||
return &ObjectStore{Client: client, Bucket: bucket, HealthURL: endpoint + "/minio/health/ready", HTTP: &http.Client{Transport: transport, Timeout: time.Second}}, nil
|
||||
}
|
||||
func (o *ObjectStore) Ready(ctx context.Context) bool {
|
||||
r, e := http.NewRequestWithContext(ctx, "GET", o.HealthURL, nil)
|
||||
if e != nil {
|
||||
return false
|
||||
}
|
||||
resp, e := o.HTTP.Do(r)
|
||||
if e != nil {
|
||||
return false
|
||||
}
|
||||
resp.Body.Close()
|
||||
return resp.StatusCode == 200
|
||||
}
|
||||
func (s *Server) SetObjectStore(o *ObjectStore) { s.objects = o; s.uploads = make(chan struct{}, 1) }
|
||||
|
||||
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"`
|
||||
Size 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"`
|
||||
}
|
||||
|
||||
const attachmentColumns = `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.object_key,a.status,a.error_code,a.variants`
|
||||
|
||||
func scanAttachment(row scanner) (Attachment, string, error) {
|
||||
a := Attachment{Status: "ready", Variants: []Variant{}}
|
||||
var c, u time.Time
|
||||
var key string
|
||||
var variants []byte
|
||||
e := row.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.Size, &a.SHA256, &c, &u, &key, &a.Status, &a.ErrorCode, &variants)
|
||||
if e == nil {
|
||||
e = json.Unmarshal(variants, &a.Variants)
|
||||
}
|
||||
a.CreatedAt = stamp(c)
|
||||
a.UpdatedAt = stamp(u)
|
||||
return a, key, e
|
||||
}
|
||||
func validFilename(name string) bool {
|
||||
if !validText(name, 255) {
|
||||
return false
|
||||
}
|
||||
for _, c := range name {
|
||||
if c == '/' || c == '\\' || unicode.IsControl(c) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// A temporary capped spool avoids holding a compressed file in RAM; it is
|
||||
// removed on every exit. DecodeConfig bounds pixels before full validation.
|
||||
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request, uid, cid string) {
|
||||
q, e := url.ParseQuery(r.URL.RawQuery)
|
||||
if e != nil || len(q["filename"]) != 1 || !validFilename(q.Get("filename")) {
|
||||
bad(w)
|
||||
return
|
||||
}
|
||||
contentType, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if e != nil || (contentType != "image/png" && contentType != "image/jpeg") {
|
||||
fail(w, 415, "unsupported_media_type", "Expected PNG or JPEG")
|
||||
return
|
||||
}
|
||||
if r.ContentLength > maxUpload {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(r.Body, maxUpload+1))
|
||||
fail(w, 413, "payload_too_large", "Maximum upload is 10 MiB")
|
||||
return
|
||||
}
|
||||
select {
|
||||
case s.uploads <- struct{}{}:
|
||||
defer func() { <-s.uploads }()
|
||||
case <-r.Context().Done():
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
f, e := os.CreateTemp("", "messenger-upload-*")
|
||||
if e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
defer os.Remove(f.Name())
|
||||
defer f.Close()
|
||||
hash := sha256.New()
|
||||
n, e := io.Copy(io.MultiWriter(f, hash), http.MaxBytesReader(w, r.Body, maxUpload))
|
||||
if e != nil {
|
||||
var over *http.MaxBytesError
|
||||
if errors.As(e, &over) {
|
||||
fail(w, 413, "payload_too_large", "Maximum upload is 10 MiB")
|
||||
} else {
|
||||
bad(w)
|
||||
}
|
||||
return
|
||||
}
|
||||
_, _ = f.Seek(0, io.SeekStart)
|
||||
config, format, e := image.DecodeConfig(f)
|
||||
if e != nil || "image/"+format != contentType {
|
||||
fail(w, 415, "unsupported_media_type", "Invalid image or MIME mismatch")
|
||||
return
|
||||
}
|
||||
if config.Width < 1 || config.Height < 1 || int64(config.Width)*int64(config.Height) > maxPixels {
|
||||
fail(w, 413, "payload_too_large", "Maximum image is 40 million pixels")
|
||||
return
|
||||
}
|
||||
_, _ = f.Seek(0, io.SeekStart)
|
||||
if !validateImage(f) {
|
||||
fail(w, 415, "unsupported_media_type", "Invalid image")
|
||||
return
|
||||
}
|
||||
_, _ = f.Seek(0, io.SeekStart)
|
||||
id := uuid()
|
||||
key := "staging/" + id
|
||||
ctx := r.Context()
|
||||
// Journal survives a crash between PUT and metadata COMMIT.
|
||||
if _, e = s.db.Exec(ctx, "INSERT INTO upload_intents(object_key) VALUES($1)", key); e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
tx, e := s.db.Begin(ctx)
|
||||
if e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,4))", key); e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
// Disable multipart: the bounded spool is <=10MiB, hence one atomic object PUT.
|
||||
_, e = s.objects.Client.PutObject(ctx, s.objects.Bucket, key, f, n, minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true})
|
||||
if e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
a, _, e := scanAttachment(tx.QueryRow(ctx, `INSERT INTO attachments AS a(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,status,staging_key) VALUES($1,$2,$3,$4,$5,$6,$7,$8,'queued',$9) RETURNING `+attachmentColumns, id, cid, uid, q.Get("filename"), "originals/"+id+"/v1/original", contentType, n, hex.EncodeToString(hash.Sum(nil)), key))
|
||||
if e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
// Admission and intent share a transaction; no unbounded accepted backlog.
|
||||
if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(2026005)"); e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
var pending int
|
||||
if e = tx.QueryRow(ctx, "SELECT count(*) FROM pipeline_jobs WHERE finished_at IS NULL").Scan(&pending); e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
if pending >= 1000 {
|
||||
w.Header().Set("Retry-After", "5")
|
||||
fail(w, 429, "rate_limited", "Processing backlog is full")
|
||||
return
|
||||
}
|
||||
parent, state := telemetry.Inject(ctx)
|
||||
if _, e = tx.Exec(ctx, `INSERT INTO pipeline_jobs(job_id,attachment_id,pipeline_version,traceparent,tracestate) VALUES($1,$2,1,$3,$4)`, uuid(), id, parent, state); e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
if _, e = tx.Exec(ctx, "DELETE FROM upload_intents WHERE object_key=$1", key); e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
reply(w, 202, a)
|
||||
}
|
||||
func validateImage(r io.Reader) bool { _, _, e := image.Decode(r); return e == nil }
|
||||
|
||||
func (s *Server) serveAttachment(w http.ResponseWriter, r *http.Request, uid string, parts []string) {
|
||||
if r.Method != "GET" || (len(parts) != 4 && len(parts) != 5) || (len(parts) == 5 && parts[4] != "content") {
|
||||
missing(w)
|
||||
return
|
||||
}
|
||||
id := strings.ToLower(parts[3])
|
||||
if !uuidRE.MatchString(id) {
|
||||
bad(w)
|
||||
return
|
||||
}
|
||||
a, key, e := scanAttachment(s.db.QueryRow(r.Context(), `SELECT `+attachmentColumns+` FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id AND m.user_id=$2 WHERE a.id=$1`, id, uid))
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
missing(w)
|
||||
return
|
||||
}
|
||||
if e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
if len(parts) == 4 {
|
||||
reply(w, 200, a)
|
||||
return
|
||||
}
|
||||
q, e := url.ParseQuery(r.URL.RawQuery)
|
||||
if e != nil || len(q["variant"]) > 1 {
|
||||
bad(w)
|
||||
return
|
||||
}
|
||||
if a.Status != "ready" {
|
||||
fail(w, 409, "conflict", "Attachment is not ready")
|
||||
return
|
||||
}
|
||||
variant := q.Get("variant")
|
||||
if variant != "" && variant != "original" {
|
||||
found := false
|
||||
for _, v := range a.Variants {
|
||||
if v.Name == variant {
|
||||
a.ContentType = v.ContentType
|
||||
a.Size = v.Size
|
||||
key = strings.TrimSuffix(key, "original") + variant
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
missing(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
object, e := s.objects.Client.GetObject(r.Context(), s.objects.Bucket, key, minio.GetObjectOptions{})
|
||||
if e != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
defer object.Close()
|
||||
info, e := object.Stat()
|
||||
if e != nil || info.Size != a.Size {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", a.ContentType)
|
||||
w.Header().Set("Content-Length", fmt.Sprint(a.Size))
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": a.Filename}))
|
||||
w.WriteHeader(200)
|
||||
_, _ = io.Copy(w, object)
|
||||
}
|
||||
|
||||
// Normalize optional attachments before hashing; JSON key ordering is irrelevant.
|
||||
func parseMessage(w http.ResponseWriter, r *http.Request) (string, []string, bool) {
|
||||
var in struct {
|
||||
Text *string `json:"text"`
|
||||
Attachments []string `json:"attachment_ids"`
|
||||
}
|
||||
// strict decoder accepts an explicitly optional field (suffix '?').
|
||||
if !decode(w, r, &in, "text", "attachment_ids?") {
|
||||
return "", nil, false
|
||||
}
|
||||
if in.Text == nil || !utf8.ValidString(*in.Text) || utf8.RuneCountInString(*in.Text) > 4000 || len(in.Attachments) > 10 || (strings.TrimSpace(*in.Text) == "" && len(in.Attachments) == 0) {
|
||||
bad(w)
|
||||
return "", nil, false
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for i, id := range in.Attachments {
|
||||
id = strings.ToLower(id)
|
||||
if !uuidRE.MatchString(id) || seen[id] {
|
||||
bad(w)
|
||||
return "", nil, false
|
||||
}
|
||||
seen[id] = true
|
||||
in.Attachments[i] = id
|
||||
}
|
||||
if in.Attachments == nil {
|
||||
in.Attachments = []string{}
|
||||
}
|
||||
return *in.Text, in.Attachments, true
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Shared PG counters, not per-process memory or untrusted forwarding headers.
|
||||
// Unknown and known usernames use the same hash/bucket and admission rules.
|
||||
func (s *Server) admitAuth(w http.ResponseWriter, r *http.Request, username string) bool {
|
||||
key := fmt.Sprintf("%x", sha256.Sum256([]byte(username)))
|
||||
var allowed bool
|
||||
if e := s.db.QueryRow(r.Context(), "SELECT auth_admit($1)", key).Scan(&allowed); e != nil {
|
||||
unavailable(w)
|
||||
return false
|
||||
}
|
||||
if !allowed {
|
||||
w.Header().Set("Retry-After", "60")
|
||||
fail(w, 429, "rate_limited", "Authentication rate limit exceeded")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//go:build linux
|
||||
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func configureChild(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
cmd.Cancel = func() error {
|
||||
if cmd.Process != nil {
|
||||
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !linux
|
||||
|
||||
package messenger
|
||||
|
||||
import "os/exec"
|
||||
|
||||
func configureChild(cmd *exec.Cmd) {}
|
||||
@@ -0,0 +1,163 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mtusi/messenger/internal/database"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Real PostgreSQL + HTTP + the race detector, in the optional Compose tests
|
||||
// service. Local go test skips this test unless the DB secret path is supplied.
|
||||
func TestDatabaseConcurrentHTTP(t *testing.T) {
|
||||
path := os.Getenv("DATABASE_TEST_URL_FILE")
|
||||
if path == "" {
|
||||
t.Skip("run make test-race for real PostgreSQL HTTP integration")
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
pool, err := database.Open(ctx, strings.TrimSpace(string(raw)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err = database.Migrate(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
api := New(pool, nil, make([]byte, 32), 3600, nil)
|
||||
ts := httptest.NewServer(api)
|
||||
defer ts.Close()
|
||||
call := func(method, path, body, auth string, status int) map[string]any {
|
||||
t.Helper()
|
||||
r, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return nil
|
||||
}
|
||||
if body != "" {
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
r.Header.Set("Authorization", auth)
|
||||
if method == "POST" && strings.HasSuffix(path, "/messages") {
|
||||
r.Header.Set("Idempotency-Key", uuid())
|
||||
}
|
||||
response, err := ts.Client().Do(r)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return nil
|
||||
}
|
||||
defer response.Body.Close()
|
||||
b, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return nil
|
||||
}
|
||||
if response.StatusCode != status {
|
||||
t.Errorf("%s %s: want %d got %d", method, path, status, response.StatusCode)
|
||||
return nil
|
||||
}
|
||||
var v map[string]any
|
||||
if err = json.Unmarshal(b, &v); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
username := "go_" + strings.ReplaceAll(uuid(), "-", "")[:20]
|
||||
user := call("POST", "/api/v1/users", fmt.Sprintf(`{"username":%q,"display_name":"Race","password":"Synthetic-Go-Test-123"}`, username), "", 201)
|
||||
if user == nil {
|
||||
t.Fatal("create failed")
|
||||
}
|
||||
basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":Synthetic-Go-Test-123"))
|
||||
session := call("POST", "/api/v1/auth/sessions", "", basic, 201)
|
||||
if session == nil {
|
||||
t.Fatal("login failed")
|
||||
}
|
||||
bearer := "Bearer " + session["token"].(string)
|
||||
chat := call("POST", "/api/v1/chats", fmt.Sprintf(`{"title":"Race","member_ids":[%q]}`, user["id"]), bearer, 201)
|
||||
if chat == nil {
|
||||
t.Fatal("chat failed")
|
||||
}
|
||||
messages := "/api/v1/chats/" + chat["id"].(string) + "/messages"
|
||||
var wg sync.WaitGroup
|
||||
for worker := 0; worker < 10; worker++ {
|
||||
wg.Add(1)
|
||||
go func(worker int) {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 10; j++ {
|
||||
call("POST", messages, fmt.Sprintf(`{"text":"worker-%d-message-%d"}`, worker, j), bearer, 201)
|
||||
}
|
||||
}(worker)
|
||||
}
|
||||
wg.Wait()
|
||||
page := call("GET", messages+"?limit=100", "", bearer, 200)
|
||||
if page == nil {
|
||||
t.Fatal("history failed")
|
||||
}
|
||||
items := page["items"].([]any)
|
||||
if len(items) != 100 {
|
||||
t.Fatalf("expected 100 messages, got %d", len(items))
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, v := range items {
|
||||
m := v.(map[string]any)
|
||||
id := m["id"].(string)
|
||||
if seen[id] {
|
||||
t.Fatal("duplicate ID")
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
// Race a single key through the real server, then verify only one side effect.
|
||||
var repeatWG sync.WaitGroup
|
||||
ids := make(chan string, 12)
|
||||
for i := 0; i < 12; i++ {
|
||||
repeatWG.Add(1)
|
||||
go func() {
|
||||
defer repeatWG.Done()
|
||||
req, _ := http.NewRequest("POST", ts.URL+messages, strings.NewReader(`{"text":"one key"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", bearer)
|
||||
req.Header.Set("Idempotency-Key", "same-concurrent-key")
|
||||
res, err := ts.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
defer res.Body.Close()
|
||||
var m Message
|
||||
if res.StatusCode != 201 || json.NewDecoder(res.Body).Decode(&m) != nil {
|
||||
t.Error("repeat failed")
|
||||
return
|
||||
}
|
||||
ids <- m.ID
|
||||
}()
|
||||
}
|
||||
repeatWG.Wait()
|
||||
close(ids)
|
||||
var expected string
|
||||
for id := range ids {
|
||||
if expected == "" {
|
||||
expected = id
|
||||
}
|
||||
if id != expected {
|
||||
t.Error("idempotency duplicate")
|
||||
}
|
||||
}
|
||||
var count int
|
||||
if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM messages WHERE chat_id=$1", chat["id"]).Scan(&count); err != nil || count != 101 {
|
||||
t.Errorf("want 101 persisted messages, got %d: %v", count, err)
|
||||
}
|
||||
t.Log("100 confirmed messages from 10 clients through real HTTP and PostgreSQL; race detector enabled")
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Operator-only CLI. It exposes no unauthenticated HTTP mutation endpoint.
|
||||
func (p *Pipeline) Replay(ctx context.Context, id string, newVersion bool) error {
|
||||
if !uuidRE.MatchString(id) {
|
||||
return fmt.Errorf("expected attachment UUID")
|
||||
}
|
||||
tx, e := p.DB.Begin(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var status, key, stage string
|
||||
var version int
|
||||
e = tx.QueryRow(ctx, `SELECT status,object_key,COALESCE(staging_key,''),pipeline_version FROM attachments WHERE id=$1 FOR UPDATE`, id).Scan(&status, &key, &stage, &version)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if newVersion {
|
||||
if status != "ready" && status != "queued" && status != "processing" {
|
||||
return fmt.Errorf("replay failed before version upgrade")
|
||||
}
|
||||
if version >= 2 {
|
||||
return fmt.Errorf("supported pipeline versions: 1 and 2")
|
||||
}
|
||||
version++
|
||||
if status == "ready" {
|
||||
stage = key
|
||||
}
|
||||
} else {
|
||||
if status != "failed" {
|
||||
return fmt.Errorf("only failed can be replayed")
|
||||
}
|
||||
}
|
||||
if _, e = p.Objects.Client.StatObject(ctx, p.Objects.Bucket, stage, minio.StatObjectOptions{}); e != nil {
|
||||
return fmt.Errorf("source unavailable; restore before replay")
|
||||
}
|
||||
var jobID string
|
||||
if newVersion {
|
||||
jobID = uuid()
|
||||
if _, e = tx.Exec(ctx, "UPDATE pipeline_jobs SET finished_at=clock_timestamp() WHERE attachment_id=$1 AND finished_at IS NULL", id); e != nil {
|
||||
return e
|
||||
}
|
||||
_, e = tx.Exec(ctx, `INSERT INTO pipeline_jobs(job_id,attachment_id,pipeline_version) VALUES($1,$2,$3)`, jobID, id, version)
|
||||
} else {
|
||||
e = tx.QueryRow(ctx, `UPDATE pipeline_jobs SET attempt=0,lease_token=NULL,lease_until=NULL,published_at=NULL,finished_at=NULL,next_attempt_at=clock_timestamp() WHERE attachment_id=$1 AND pipeline_version=$2 RETURNING job_id::text`, id, version).Scan(&jobID)
|
||||
}
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
_, e = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,variants='[]',pipeline_version=$2,staging_key=$3,updated_at=clock_timestamp() WHERE id=$1`, id, version, stage)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
event := "operator_replay"
|
||||
if newVersion {
|
||||
event = "operator_new_version"
|
||||
}
|
||||
if _, e = tx.Exec(ctx, `INSERT INTO pipeline_audit(job_id,event,attempt) VALUES($1,$2,0)`, jobID, event); e != nil {
|
||||
return e
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
// Only staging is collected automatically. Live queued/processing work and final
|
||||
// objects are always protected. Ready stage is redundant; failed source has 7d
|
||||
// retention. Unattributed aborted uploads/intents have a conservative 24h grace.
|
||||
func (p *Pipeline) Cleanup(ctx context.Context, apply bool) error {
|
||||
for object := range p.Objects.Client.ListObjects(ctx, p.Objects.Bucket, minio.ListObjectsOptions{Prefix: "staging/", Recursive: true}) {
|
||||
if object.Err != nil {
|
||||
return object.Err
|
||||
}
|
||||
if time.Since(object.LastModified) < 24*time.Hour {
|
||||
continue
|
||||
}
|
||||
tx, e := p.DB.Begin(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,4))", object.Key); e != nil {
|
||||
tx.Rollback(ctx)
|
||||
return e
|
||||
}
|
||||
var status string
|
||||
var updated time.Time
|
||||
e = tx.QueryRow(ctx, `SELECT status,updated_at FROM attachments WHERE staging_key=$1 FOR UPDATE`, object.Key).Scan(&status, &updated)
|
||||
if e != nil && !errors.Is(e, pgx.ErrNoRows) {
|
||||
tx.Rollback(ctx)
|
||||
return e
|
||||
}
|
||||
safe := errors.Is(e, pgx.ErrNoRows) || status == "ready" || (status == "failed" && time.Since(updated) > 7*24*time.Hour)
|
||||
if safe {
|
||||
p.Log.Info("staging_cleanup", "event", "staging_cleanup", "apply", apply, "status", status)
|
||||
if apply {
|
||||
if e = p.Objects.Client.RemoveObject(ctx, p.Objects.Bucket, object.Key, minio.RemoveObjectOptions{}); e != nil {
|
||||
tx.Rollback(ctx)
|
||||
return e
|
||||
}
|
||||
if _, e = tx.Exec(ctx, `DELETE FROM upload_intents WHERE object_key=$1`, object.Key); e != nil {
|
||||
tx.Rollback(ctx)
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (p *Pipeline) RunHousekeeping(ctx context.Context) error {
|
||||
for ctx.Err() == nil {
|
||||
if e := p.Cleanup(ctx, true); e != nil {
|
||||
p.Log.Warn("cleanup_retry", "event", "cleanup_retry")
|
||||
}
|
||||
if !wait(ctx, time.Hour) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func ParseOperatorArgs(args []string) (string, bool, error) {
|
||||
if len(args) != 1 || strings.TrimSpace(args[0]) == "" {
|
||||
return "", false, fmt.Errorf("expected one attachment UUID")
|
||||
}
|
||||
return args[0], false, nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"golang.org/x/crypto/argon2"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Fixed, bounded parameters: 64 MiB, 3 passes, 2 lanes, 16-byte salt,
|
||||
// 32-byte result. The HTTP layer bounds simultaneous KDF work to 2 calls.
|
||||
func hashPassword(password string) string {
|
||||
salt := make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt, 3, 64*1024, 2, 32)
|
||||
return "$argon2id$v=19$m=65536,t=3,p=2$" + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash)
|
||||
}
|
||||
func verifyPassword(password, encoded string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" {
|
||||
return false
|
||||
}
|
||||
var memory, passes, lanes uint32
|
||||
if n, e := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &passes, &lanes); e != nil || n != 3 || parts[3] != fmt.Sprintf("m=%d,t=%d,p=%d", memory, passes, lanes) || memory < 8192 || memory > 65536 || passes < 1 || passes > 3 || lanes < 1 || lanes > 2 {
|
||||
return false
|
||||
}
|
||||
salt, e1 := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
want, e2 := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if e1 != nil || e2 != nil || len(salt) != 16 || len(want) != 32 {
|
||||
return false
|
||||
}
|
||||
got := argon2.IDKey([]byte(password), salt, passes, memory, uint8(lanes), 32)
|
||||
return subtle.ConstantTimeCompare(got, want) == 1
|
||||
}
|
||||
|
||||
func needsRehash(hash string) bool {
|
||||
return !strings.HasPrefix(hash, "$argon2id$v=19$m=65536,t=3,p=2$")
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPasswordFullUnicodeRange(t *testing.T) {
|
||||
password := strings.Repeat("🙂", 128) // 512 bytes: exceeds bcrypt's 72-byte limit.
|
||||
hash := hashPassword(password)
|
||||
if !verifyPassword(password, hash) || verifyPassword(password+"x", hash) {
|
||||
t.Fatal("password mismatch")
|
||||
}
|
||||
if hash == hashPassword(password) {
|
||||
t.Fatal("salt reused")
|
||||
}
|
||||
if verifyPassword(password, "$argon2id$v=19$m=999999999,t=3,p=2$abc$def") {
|
||||
t.Fatal("unbounded parameters accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math/rand/v2"
|
||||
"mtusi/messenger/internal/telemetry"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const stream = "attachment.jobs.v1"
|
||||
const group = "image-workers"
|
||||
const maxAttempts = 5
|
||||
const leaseSeconds = 45
|
||||
|
||||
type Job struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
ID string `json:"job_id"`
|
||||
Type string `json:"type"`
|
||||
AttachmentID string `json:"attachment_id"`
|
||||
Version int `json:"pipeline_version"`
|
||||
Attempt int `json:"attempt"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
Traceparent string `json:"traceparent,omitempty"`
|
||||
Tracestate string `json:"tracestate,omitempty"`
|
||||
}
|
||||
type Pipeline struct {
|
||||
DB *pgxpool.Pool
|
||||
Broker *redis.Client
|
||||
Objects *ObjectStore
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
func NewPipeline(db *pgxpool.Pool, broker *redis.Client, o *ObjectStore, log *slog.Logger) *Pipeline {
|
||||
return &Pipeline{db, broker, o, log}
|
||||
}
|
||||
func wait(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-t.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
func (p *Pipeline) RunDispatcher(ctx context.Context) error {
|
||||
for ctx.Err() == nil {
|
||||
if e := p.dispatch(ctx); e != nil {
|
||||
p.Log.Warn("outbox_retry", "event", "outbox_retry")
|
||||
}
|
||||
if !wait(ctx, 500*time.Millisecond) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (p *Pipeline) dispatch(ctx context.Context) error {
|
||||
// Small per-row transaction + SKIP LOCKED allows multiple dispatchers. A crash
|
||||
// after XADD before COMMIT gives a duplicate, never a missing durable intent.
|
||||
for i := 0; i < 32; i++ {
|
||||
tx, e := p.DB.Begin(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
var j Job
|
||||
var created time.Time
|
||||
e = tx.QueryRow(ctx, `SELECT job_id::text,attachment_id::text,pipeline_version,attempt+1,created_at,traceparent,tracestate FROM pipeline_jobs WHERE finished_at IS NULL AND next_attempt_at<=clock_timestamp() AND (lease_until IS NULL OR lease_until<clock_timestamp()) AND (published_at IS NULL OR published_at<clock_timestamp()-interval '60 seconds') ORDER BY next_attempt_at FOR UPDATE SKIP LOCKED LIMIT 1`).Scan(&j.ID, &j.AttachmentID, &j.Version, &j.Attempt, &created, &j.Traceparent, &j.Tracestate)
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
tx.Rollback(ctx)
|
||||
return nil
|
||||
}
|
||||
if e != nil {
|
||||
tx.Rollback(ctx)
|
||||
return e
|
||||
}
|
||||
j.SchemaVersion = 1
|
||||
j.Type = "attachment.process.v1"
|
||||
j.CreatedAt = stamp(created)
|
||||
publishCtx, span := telemetry.Start(telemetry.Extract(ctx, j.Traceparent, j.Tracestate), "queue.publish", trace.SpanKindProducer)
|
||||
span.SetAttributes(attribute.String("messaging.system", "valkey"), attribute.String("messaging.destination.name", stream))
|
||||
j.Traceparent, j.Tracestate = telemetry.Inject(publishCtx)
|
||||
payload, _ := json.Marshal(j)
|
||||
_, e = p.Broker.XAdd(publishCtx, &redis.XAddArgs{Stream: stream, Values: map[string]any{"payload": string(payload)}}).Result()
|
||||
telemetry.Failure(span, e)
|
||||
span.End()
|
||||
if e == nil {
|
||||
_, e = tx.Exec(ctx, "UPDATE pipeline_jobs SET published_at=clock_timestamp() WHERE job_id=$1", j.ID)
|
||||
}
|
||||
if e != nil {
|
||||
tx.Rollback(ctx)
|
||||
return e
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return e
|
||||
}
|
||||
p.Log.InfoContext(publishCtx, "job_published", "event", "job_published", "job_id", j.ID, "pipeline_version", j.Version)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (p *Pipeline) RunWorker(ctx context.Context, concurrency int) error {
|
||||
if concurrency < 1 || concurrency > 4 {
|
||||
return fmt.Errorf("WORKER_CONCURRENCY must be 1..4")
|
||||
}
|
||||
for ctx.Err() == nil {
|
||||
e := p.Broker.XGroupCreateMkStream(ctx, stream, group, "0").Err()
|
||||
if e == nil || strings.Contains(e.Error(), "BUSYGROUP") {
|
||||
break
|
||||
}
|
||||
if !wait(ctx, time.Second) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
telemetry.WorkerCapacity(concurrency)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < concurrency; i++ {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); p.consume(ctx, uuid()) }()
|
||||
}
|
||||
wg.Wait()
|
||||
return nil
|
||||
}
|
||||
func (p *Pipeline) consume(ctx context.Context, consumer string) {
|
||||
cursor := "0-0"
|
||||
for ctx.Err() == nil {
|
||||
claimed, next, e := p.Broker.XAutoClaim(ctx, &redis.XAutoClaimArgs{Stream: stream, Group: group, Consumer: consumer, MinIdle: time.Minute, Start: cursor, Count: 1}).Result()
|
||||
cursor = next
|
||||
if e == nil && len(claimed) > 0 {
|
||||
p.handle(ctx, claimed[0])
|
||||
continue
|
||||
}
|
||||
entries, e := p.Broker.XReadGroup(ctx, &redis.XReadGroupArgs{Group: group, Consumer: consumer, Streams: []string{stream, ">"}, Count: 1, Block: time.Second}).Result()
|
||||
if e != nil {
|
||||
if e != redis.Nil {
|
||||
wait(ctx, time.Second)
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, entry := range entries {
|
||||
for _, m := range entry.Messages {
|
||||
p.handle(ctx, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func (p *Pipeline) handle(ctx context.Context, m redis.XMessage) {
|
||||
raw, _ := m.Values["payload"].(string)
|
||||
var j Job
|
||||
d := json.NewDecoder(strings.NewReader(raw))
|
||||
d.DisallowUnknownFields()
|
||||
if len(raw) > 4096 || d.Decode(&j) != nil || j.SchemaVersion != 1 || j.Type != "attachment.process.v1" || !uuidRE.MatchString(j.ID) || !uuidRE.MatchString(j.AttachmentID) || j.Version < 1 || j.Attempt < 1 {
|
||||
p.Log.Warn("invalid_job", "event", "invalid_job")
|
||||
p.ack(ctx, m.ID)
|
||||
return
|
||||
}
|
||||
// The authoritative attempt and storage locations come from PostgreSQL, never
|
||||
// from untrusted broker payload fields. A terminal/stale delivery is a no-op.
|
||||
ctx, span := telemetry.Start(telemetry.Extract(ctx, j.Traceparent, j.Tracestate), "queue.consume", trace.SpanKindConsumer)
|
||||
defer span.End()
|
||||
done, e := p.process(ctx, j)
|
||||
telemetry.Failure(span, e)
|
||||
if e != nil {
|
||||
p.Log.WarnContext(ctx, "job_deferred", "event", "job_deferred", "job_id", j.ID)
|
||||
}
|
||||
if done {
|
||||
p.ack(ctx, m.ID)
|
||||
}
|
||||
}
|
||||
func (p *Pipeline) ack(ctx context.Context, id string) {
|
||||
// Do not delete an entry unless ACK succeeded; the only consumer group is ours.
|
||||
if p.Broker.XAck(ctx, stream, group, id).Err() == nil {
|
||||
p.Broker.XDel(ctx, stream, id)
|
||||
}
|
||||
}
|
||||
func (p *Pipeline) process(parent context.Context, j Job) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(parent, 30*time.Second)
|
||||
defer cancel()
|
||||
tx, e := p.DB.Begin(ctx)
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var status, key, sha, contentType string
|
||||
var version, attempt int
|
||||
var size int64
|
||||
var lease *time.Time
|
||||
e = tx.QueryRow(ctx, `SELECT a.status,a.pipeline_version,a.staging_key,a.sha256,a.content_type,a.size_bytes,j.attempt,j.lease_until FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=$1 AND j.attachment_id=$2 AND j.pipeline_version=$3 FOR UPDATE OF j,a`, j.ID, j.AttachmentID, j.Version).Scan(&status, &version, &key, &sha, &contentType, &size, &attempt, &lease)
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
return true, nil
|
||||
}
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
if version != j.Version || status == "ready" || status == "failed" {
|
||||
return true, nil
|
||||
}
|
||||
var now time.Time
|
||||
if e = tx.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); e != nil {
|
||||
return false, e
|
||||
}
|
||||
if lease != nil && lease.After(now) {
|
||||
return true, nil
|
||||
} // live attempt; DB recovery remains durable
|
||||
if attempt >= maxAttempts {
|
||||
_, e = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=$1;`, j.AttachmentID)
|
||||
if e == nil {
|
||||
_, e = tx.Exec(ctx, "UPDATE pipeline_jobs SET finished_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1", j.ID)
|
||||
}
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
token := uuid()
|
||||
attempt++
|
||||
if _, e = tx.Exec(ctx, `UPDATE pipeline_jobs SET attempt=$2,lease_token=$3,lease_until=clock_timestamp()+interval '45 seconds' WHERE job_id=$1`, j.ID, attempt, token); e != nil {
|
||||
return false, e
|
||||
}
|
||||
if _, e = tx.Exec(ctx, `UPDATE attachments SET status='processing',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID); e != nil {
|
||||
return false, e
|
||||
}
|
||||
if _, e = tx.Exec(ctx, `INSERT INTO pipeline_audit(job_id,event,attempt) VALUES($1,'claimed',$2)`, j.ID, attempt); e != nil {
|
||||
return false, e
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return false, e
|
||||
}
|
||||
trace.SpanFromContext(ctx).SetAttributes(attribute.Int("job.attempt", attempt), attribute.Int("pipeline.version", j.Version))
|
||||
attemptStart := time.Now()
|
||||
outcome := "failure"
|
||||
defer func() {
|
||||
trace.SpanFromContext(ctx).SetAttributes(attribute.String("job.outcome", outcome))
|
||||
telemetry.Job(ctx, outcome, time.Since(attemptStart).Seconds())
|
||||
}()
|
||||
p.Log.InfoContext(ctx, "job_started", "event", "job_started", "job_id", j.ID, "attempt", attempt, "pipeline_version", j.Version)
|
||||
faultPoint("before_objects")
|
||||
telemetry.Busy.Add(1)
|
||||
variants, processErr := p.perform(ctx, j, key, sha, contentType, size)
|
||||
telemetry.Busy.Add(-1)
|
||||
telemetry.Failure(trace.SpanFromContext(ctx), processErr)
|
||||
if processErr == nil {
|
||||
faultPoint("after_objects")
|
||||
}
|
||||
// A short independent commit budget allows recording a timed-out attempt;
|
||||
// a cancelled/killed process instead recovers via the persisted lease.
|
||||
finish, stop := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)
|
||||
defer stop()
|
||||
tx, e = p.DB.Begin(finish)
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var currentToken *string
|
||||
var currentVersion int
|
||||
e = tx.QueryRow(finish, `SELECT j.lease_token::text,a.pipeline_version FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=$1 FOR UPDATE OF j,a`, j.ID).Scan(¤tToken, ¤tVersion)
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
if currentToken == nil || *currentToken != token || currentVersion != j.Version {
|
||||
return true, nil
|
||||
}
|
||||
if processErr == nil {
|
||||
encoded, _ := json.Marshal(variants)
|
||||
_, e = tx.Exec(finish, `UPDATE attachments SET status='ready',error_code=NULL,variants=$2,object_key=$3,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID, encoded, resultPrefix(j)+"original")
|
||||
if e == nil {
|
||||
_, e = tx.Exec(finish, `UPDATE pipeline_jobs SET finished_at=clock_timestamp(),ready_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1`, j.ID)
|
||||
}
|
||||
} else {
|
||||
permanent := errors.Is(processErr, errInvalidImage)
|
||||
if permanent || attempt >= maxAttempts {
|
||||
code := "retry_exhausted"
|
||||
if permanent {
|
||||
code = "invalid_image"
|
||||
}
|
||||
_, e = tx.Exec(finish, `UPDATE attachments SET status='failed',error_code=$2,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID, code)
|
||||
if e == nil {
|
||||
_, e = tx.Exec(finish, `UPDATE pipeline_jobs SET finished_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1`, j.ID)
|
||||
}
|
||||
} else {
|
||||
_, e = tx.Exec(finish, `UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID)
|
||||
delay := time.Duration(1<<attempt)*time.Second + time.Duration(rand.IntN(1000))*time.Millisecond
|
||||
if e == nil {
|
||||
_, e = tx.Exec(finish, `UPDATE pipeline_jobs SET lease_until=NULL,published_at=NULL,next_attempt_at=clock_timestamp()+$2::interval WHERE job_id=$1`, j.ID, fmt.Sprintf("%f seconds", delay.Seconds()))
|
||||
}
|
||||
}
|
||||
}
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
event := "ready"
|
||||
if processErr != nil {
|
||||
event = "processing_error"
|
||||
}
|
||||
if _, e = tx.Exec(finish, `INSERT INTO pipeline_audit(job_id,event,attempt) VALUES($1,$2,$3)`, j.ID, event, attempt); e != nil {
|
||||
return false, e
|
||||
}
|
||||
if e = tx.Commit(finish); e != nil {
|
||||
return false, e
|
||||
}
|
||||
var since float64
|
||||
if processErr == nil && p.DB.QueryRow(finish, "SELECT EXTRACT(EPOCH FROM ready_at-created_at)::float8 FROM pipeline_jobs WHERE job_id=$1", j.ID).Scan(&since) == nil {
|
||||
telemetry.Ready(ctx, since)
|
||||
}
|
||||
p.Log.InfoContext(ctx, "job_completed", "event", "job_completed", "job_id", j.ID, "outcome", event, "attempt", attempt)
|
||||
if processErr == nil {
|
||||
outcome = "success"
|
||||
faultPoint("after_commit")
|
||||
// Committed ready points only at final objects. Cleanup failure is retried
|
||||
// by the housekeeping pass; staging is never deleted before ready COMMIT.
|
||||
if strings.HasPrefix(key, "staging/") {
|
||||
_ = p.Objects.Client.RemoveObject(finish, p.Objects.Bucket, key, minio.RemoveObjectOptions{})
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
var ErrInvalidImage = errors.New("invalid_image")
|
||||
var errInvalidImage = ErrInvalidImage
|
||||
|
||||
func resultPrefix(j Job) string {
|
||||
return "originals/" + j.AttachmentID + "/v" + strconv.Itoa(j.Version) + "/"
|
||||
}
|
||||
func (p *Pipeline) perform(ctx context.Context, j Job, key, sha, contentType string, size int64) ([]Variant, error) {
|
||||
dir, e := os.MkdirTemp("", "messenger-job-*")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
object, e := p.Objects.Client.GetObject(ctx, p.Objects.Bucket, key, minio.GetObjectOptions{})
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer object.Close()
|
||||
f, e := os.Create(filepath.Join(dir, "input"))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
h := sha256.New()
|
||||
n, e := io.Copy(io.MultiWriter(f, h), io.LimitReader(object, maxUpload+1))
|
||||
f.Close()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if n != size || hex.EncodeToString(h.Sum(nil)) != sha {
|
||||
return nil, errInvalidImage
|
||||
}
|
||||
executable, e := os.Executable()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
transformCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(transformCtx, executable, "transform", filepath.Join(dir, "input"), dir, strconv.Itoa(j.Version))
|
||||
// Descendant cwebp inherits the process group; negative-PGID kill prevents
|
||||
// an orphan encoder outliving the transform deadline (Linux container only).
|
||||
configureChild(cmd)
|
||||
transformCtx, transformSpan := telemetry.Start(transformCtx, "image.transform", trace.SpanKindInternal)
|
||||
_ = transformCtx
|
||||
e = cmd.Run()
|
||||
telemetry.Failure(transformSpan, e)
|
||||
transformSpan.End()
|
||||
if e != nil {
|
||||
return nil, classifyTransformFailure(transformCtx.Err(), e)
|
||||
}
|
||||
raw, e := os.ReadFile(filepath.Join(dir, "variants.json"))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
var variants []Variant
|
||||
if e = json.Unmarshal(raw, &variants); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
input, e := os.Open(filepath.Join(dir, "input"))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer input.Close()
|
||||
faultPoint("before_write")
|
||||
if _, e = p.Objects.Client.PutObject(ctx, p.Objects.Bucket, resultPrefix(j)+"original", input, size, minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true}); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
for i, v := range variants {
|
||||
b, e := os.ReadFile(filepath.Join(dir, v.Name))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
digest := sha256.Sum256(b)
|
||||
variants[i].SHA256 = hex.EncodeToString(digest[:])
|
||||
variants[i].Size = int64(len(b))
|
||||
_, e = p.Objects.Client.PutObject(ctx, p.Objects.Bucket, resultPrefix(j)+v.Name, bytes.NewReader(b), int64(len(b)), minio.PutObjectOptions{ContentType: v.ContentType, DisableMultipart: true})
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
return variants, nil
|
||||
}
|
||||
|
||||
// Opt-in local fault injection is absent from the normal Compose environment.
|
||||
// A marker allows tests to observe the real boundary before killing the worker.
|
||||
func faultPoint(point string) {
|
||||
if os.Getenv("LAB_FAULT_POINT") == point {
|
||||
_ = os.WriteFile("/tmp/fault-reached", []byte(point), 0600)
|
||||
for {
|
||||
if _, e := os.Stat("/tmp/fault-release"); e == nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A killed/crashed encoder is not evidence of an invalid source image.
|
||||
func classifyTransformFailure(deadline, errorResult error) error {
|
||||
if deadline != nil {
|
||||
return deadline
|
||||
}
|
||||
var exited *exec.ExitError
|
||||
if errors.As(errorResult, &exited) && exited.ExitCode() == 65 {
|
||||
return ErrInvalidImage
|
||||
}
|
||||
return fmt.Errorf("transform temporarily unavailable")
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"github.com/disintegration/imaging"
|
||||
"image"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// imaging handles JPEG APP1 orientation. PNG stores the same TIFF data in eXIf.
|
||||
// Read only inside the already capped upload, with bounds checks on every IFD.
|
||||
func pngOrientation(path string) int {
|
||||
f, e := os.Open(path)
|
||||
if e != nil {
|
||||
return 1
|
||||
}
|
||||
defer f.Close()
|
||||
if _, e = f.Seek(8, io.SeekStart); e != nil {
|
||||
return 1
|
||||
}
|
||||
for {
|
||||
var h [8]byte
|
||||
if _, e = io.ReadFull(f, h[:]); e != nil {
|
||||
return 1
|
||||
}
|
||||
n := binary.BigEndian.Uint32(h[:4])
|
||||
if n > maxUpload {
|
||||
return 1
|
||||
}
|
||||
if string(h[4:]) == "eXIf" {
|
||||
b := make([]byte, n)
|
||||
if _, e = io.ReadFull(f, b); e != nil {
|
||||
return 1
|
||||
}
|
||||
return tiffOrientation(b)
|
||||
}
|
||||
if string(h[4:]) == "IEND" {
|
||||
return 1
|
||||
}
|
||||
if _, e = f.Seek(int64(n)+4, io.SeekCurrent); e != nil {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
}
|
||||
func tiffOrientation(b []byte) int {
|
||||
if len(b) < 8 {
|
||||
return 1
|
||||
}
|
||||
var order binary.ByteOrder
|
||||
switch string(b[:2]) {
|
||||
case "II":
|
||||
order = binary.LittleEndian
|
||||
case "MM":
|
||||
order = binary.BigEndian
|
||||
default:
|
||||
return 1
|
||||
}
|
||||
if order.Uint16(b[2:4]) != 42 {
|
||||
return 1
|
||||
}
|
||||
offset := uint64(order.Uint32(b[4:8]))
|
||||
if offset+2 > uint64(len(b)) {
|
||||
return 1
|
||||
}
|
||||
count := int(order.Uint16(b[offset : offset+2]))
|
||||
for i := 0; i < count; i++ {
|
||||
pos := offset + 2 + uint64(i)*12
|
||||
if pos+12 > uint64(len(b)) {
|
||||
return 1
|
||||
}
|
||||
entry := b[pos : pos+12]
|
||||
if order.Uint16(entry[:2]) == 0x112 && order.Uint16(entry[2:4]) == 3 && order.Uint32(entry[4:8]) == 1 {
|
||||
v := int(order.Uint16(entry[8:10]))
|
||||
if v >= 1 && v <= 8 {
|
||||
return v
|
||||
}
|
||||
return 1
|
||||
}
|
||||
}
|
||||
return 1
|
||||
}
|
||||
func orientPNG(img image.Image, orientation int) image.Image {
|
||||
switch orientation {
|
||||
case 2:
|
||||
return imaging.FlipH(img)
|
||||
case 3:
|
||||
return imaging.Rotate180(img)
|
||||
case 4:
|
||||
return imaging.FlipV(img)
|
||||
case 5:
|
||||
return imaging.Transpose(img)
|
||||
case 6:
|
||||
return imaging.Rotate270(img)
|
||||
case 7:
|
||||
return imaging.Transverse(img)
|
||||
case 8:
|
||||
return imaging.Rotate90(img)
|
||||
}
|
||||
return img
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"golang.org/x/crypto/argon2"
|
||||
"mtusi/messenger/internal/database"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLegacyArgon2RehashOnHTTPLogin(t *testing.T) {
|
||||
raw, e := os.ReadFile(os.Getenv("DATABASE_TEST_URL_FILE"))
|
||||
if e != nil {
|
||||
t.Skip("real PostgreSQL required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
db, e := database.Open(ctx, strings.TrimSpace(string(raw)))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer db.Close()
|
||||
salt := []byte("synthetic-salt16")
|
||||
password := "Synthetic-old-password-123"
|
||||
hash := argon2.IDKey([]byte(password), salt, 2, 19456, 1, 32)
|
||||
legacy := "$argon2id$v=19$m=19456,t=2,p=1$" + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash)
|
||||
if !verifyPassword(password, legacy) || !needsRehash(legacy) {
|
||||
t.Fatal("legacy verification or upgrade missing")
|
||||
}
|
||||
username := "rehash_" + strings.ReplaceAll(uuid(), "-", "")[:16]
|
||||
id := uuid()
|
||||
_, e = db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,'Synthetic rehash',$3)", id, username, legacy)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
server := httptest.NewServer(New(db, nil, make([]byte, 32), 3600, nil))
|
||||
defer server.Close()
|
||||
req, _ := http.NewRequest("POST", server.URL+"/api/v1/auth/sessions", nil)
|
||||
req.SetBasicAuth(username, password)
|
||||
res, e := server.Client().Do(req)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode != 201 {
|
||||
t.Fatalf("login status %d", res.StatusCode)
|
||||
}
|
||||
var updated string
|
||||
if db.QueryRow(ctx, "SELECT password_hash FROM users WHERE id=$1", id).Scan(&updated) != nil || needsRehash(updated) || !verifyPassword(password, updated) {
|
||||
t.Fatal("successful login did not safely upgrade stored hash")
|
||||
}
|
||||
for _, bad := range []string{"$argon2id$v=19$m=4294967295,t=999,p=2$AA$AA", "$argon2id$v=19$m=0,t=0,p=0$AA$AA"} {
|
||||
if verifyPassword(password, bad) {
|
||||
t.Fatal("unbounded PHC accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,845 @@
|
||||
// Package messenger implements the lab6 contract. PostgreSQL is authoritative.
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"io"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"mtusi/messenger/internal/telemetry"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
type Message struct {
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
type Page[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func uuid() string {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
b[6] = (b[6] & 15) | 64
|
||||
b[8] = (b[8] & 63) | 128
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:])
|
||||
}
|
||||
|
||||
var uuidRE = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
|
||||
var usernameRE = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func validText(v string, max int) bool {
|
||||
return utf8.ValidString(v) && strings.TrimSpace(v) != "" && utf8.RuneCountInString(v) <= max
|
||||
}
|
||||
func reply(w http.ResponseWriter, status int, v any) {
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
func fail(w http.ResponseWriter, status int, code, msg string) {
|
||||
reply(w, status, map[string]any{"error": map[string]string{"code": code, "message": msg, "request_id": w.Header().Get("X-Request-Id")}})
|
||||
}
|
||||
func bad(w http.ResponseWriter) { fail(w, 400, "invalid_request", "Invalid request") }
|
||||
func missing(w http.ResponseWriter) { fail(w, 404, "not_found", "Object not found") }
|
||||
|
||||
// Decode exact object keys (encoding/json structs alone accept case variants).
|
||||
// Reject null, duplicate keys, trailing documents and invalid UTF-8 as well.
|
||||
func decode(w http.ResponseWriter, r *http.Request, dst any, fields ...string) bool {
|
||||
media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || media != "application/json" {
|
||||
fail(w, 415, "unsupported_media_type", "Expected application/json")
|
||||
return false
|
||||
}
|
||||
b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
if err != nil {
|
||||
if _, ok := err.(*http.MaxBytesError); ok {
|
||||
fail(w, 413, "payload_too_large", "Body exceeds 1 MiB")
|
||||
} else {
|
||||
bad(w)
|
||||
}
|
||||
return false
|
||||
}
|
||||
if !utf8.Valid(b) {
|
||||
bad(w)
|
||||
return false
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(b))
|
||||
token, err := d.Token()
|
||||
if err != nil || token != json.Delim('{') {
|
||||
bad(w)
|
||||
return false
|
||||
}
|
||||
allowed := map[string]bool{}
|
||||
for _, f := range fields {
|
||||
allowed[strings.TrimSuffix(f, "?")] = true
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for d.More() {
|
||||
t, e := d.Token()
|
||||
k, ok := t.(string)
|
||||
if e != nil || !ok || !allowed[k] || seen[k] {
|
||||
bad(w)
|
||||
return false
|
||||
}
|
||||
seen[k] = true
|
||||
var raw json.RawMessage
|
||||
if d.Decode(&raw) != nil || bytes.Equal(raw, []byte("null")) {
|
||||
bad(w)
|
||||
return false
|
||||
}
|
||||
}
|
||||
if _, err = d.Token(); err != nil {
|
||||
bad(w)
|
||||
return false
|
||||
}
|
||||
if _, err = d.Token(); err != io.EOF {
|
||||
bad(w)
|
||||
return false
|
||||
}
|
||||
for _, f := range fields {
|
||||
if !strings.HasSuffix(f, "?") && !seen[f] {
|
||||
bad(w)
|
||||
return false
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(b, dst) != nil {
|
||||
bad(w)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type cursor struct {
|
||||
Scope string `json:"scope"`
|
||||
Time string `json:"time"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func (s *Server) encodeCursor(c cursor) *string {
|
||||
b, _ := json.Marshal(c)
|
||||
mac := hmac.New(sha256.New, s.secret)
|
||||
mac.Write(b)
|
||||
v := base64.RawURLEncoding.EncodeToString(b) + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
||||
return &v
|
||||
}
|
||||
func (s *Server) pagination(w http.ResponseWriter, r *http.Request, scope string) (int, cursor, bool) {
|
||||
var c cursor
|
||||
limit := 50
|
||||
// ParseQuery explicitly reports malformed escaping, unlike URL.Query.
|
||||
values, e := url.ParseQuery(r.URL.RawQuery)
|
||||
if e != nil {
|
||||
bad(w)
|
||||
return 0, c, false
|
||||
}
|
||||
if v, ok := values["limit"]; ok {
|
||||
if len(v) != 1 || v[0] == "" || strings.Trim(v[0], "0123456789") != "" {
|
||||
bad(w)
|
||||
return 0, c, false
|
||||
}
|
||||
limit, e = strconv.Atoi(v[0])
|
||||
if e != nil || limit < 1 || limit > 100 {
|
||||
bad(w)
|
||||
return 0, c, false
|
||||
}
|
||||
}
|
||||
if v, ok := values["cursor"]; ok {
|
||||
if len(v) != 1 || len(v[0]) > 2048 {
|
||||
bad(w)
|
||||
return 0, c, false
|
||||
}
|
||||
parts := strings.Split(v[0], ".")
|
||||
if len(parts) != 2 {
|
||||
bad(w)
|
||||
return 0, c, false
|
||||
}
|
||||
b, e1 := base64.RawURLEncoding.DecodeString(parts[0])
|
||||
sig, e2 := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
mac := hmac.New(sha256.New, s.secret)
|
||||
mac.Write(b)
|
||||
if e1 != nil || e2 != nil || !hmac.Equal(sig, mac.Sum(nil)) || json.Unmarshal(b, &c) != nil || c.Scope != scope || !uuidRE.MatchString(c.ID) {
|
||||
bad(w)
|
||||
return 0, c, false
|
||||
}
|
||||
}
|
||||
if c.ID != "" {
|
||||
if _, err := time.Parse(time.RFC3339Nano, c.Time); err != nil {
|
||||
bad(w)
|
||||
return 0, c, false
|
||||
}
|
||||
}
|
||||
return limit, c, true
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
db *pgxpool.Pool
|
||||
cache *redis.Client
|
||||
secret []byte
|
||||
ttl int
|
||||
log *slog.Logger
|
||||
stopping atomic.Bool
|
||||
kdf chan struct{}
|
||||
objects *ObjectStore
|
||||
uploads chan struct{}
|
||||
instance string
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
func New(db *pgxpool.Pool, cache *redis.Client, secret []byte, ttl int, logger *slog.Logger) *Server {
|
||||
hostname := uuid()
|
||||
_ = os.WriteFile("/run/runtime/instance_alias", []byte(hostname), 0600)
|
||||
return &Server{instance: hostname, db: db, cache: cache, secret: secret, ttl: ttl, log: logger, kdf: make(chan struct{}, 2), dummyHash: hashPassword("dummy-not-a-real-password")}
|
||||
}
|
||||
func (s *Server) Stop() { s.stopping.Store(true) }
|
||||
func (s *Server) acquireKDF(ctx context.Context, w http.ResponseWriter) bool {
|
||||
select {
|
||||
case s.kdf <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
w.Header().Set("Retry-After", "1")
|
||||
fail(w, 429, "rate_limited", "Authentication capacity exceeded")
|
||||
return false
|
||||
}
|
||||
}
|
||||
func unavailable(w http.ResponseWriter) {
|
||||
fail(w, 503, "unavailable", "Dependency temporarily unavailable")
|
||||
}
|
||||
func unauthorized(w http.ResponseWriter, scheme string) {
|
||||
challenge := scheme + ` realm="messenger"`
|
||||
if scheme == "Basic" {
|
||||
challenge += `, charset="UTF-8"`
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", challenge)
|
||||
fail(w, 401, "unauthorized", "Invalid or missing credentials")
|
||||
}
|
||||
func stamp(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000000Z") }
|
||||
|
||||
const userColumns = "id::text, username, display_name, created_at"
|
||||
|
||||
type scanner interface{ Scan(...any) error }
|
||||
|
||||
func scanUser(row scanner) (User, error) {
|
||||
var u User
|
||||
var t time.Time
|
||||
err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &t)
|
||||
u.CreatedAt = stamp(t)
|
||||
return u, err
|
||||
}
|
||||
func scanMessage(row scanner) (Message, error) {
|
||||
var m Message
|
||||
var t time.Time
|
||||
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &t)
|
||||
m.CreatedAt = stamp(t)
|
||||
m.AttachmentIDs = []string{}
|
||||
return m, err
|
||||
}
|
||||
|
||||
func (s *Server) profile(ctx context.Context, uid string) (User, error) {
|
||||
// Valkey caches ONLY immutable User JSON. Session validity is always read
|
||||
// from PostgreSQL first; cache loss never permits anonymous access.
|
||||
key := "profile:v1:" + uid
|
||||
if s.cache != nil {
|
||||
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
|
||||
raw, err := s.cache.Get(c, key).Bytes()
|
||||
cancel()
|
||||
var u User
|
||||
if err == nil && json.Unmarshal(raw, &u) == nil && u.ID == uid {
|
||||
return u, nil
|
||||
}
|
||||
}
|
||||
u, err := scanUser(s.db.QueryRow(ctx, "SELECT "+userColumns+" FROM users WHERE id=$1", uid))
|
||||
if err != nil {
|
||||
return u, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
raw, _ := json.Marshal(u)
|
||||
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
|
||||
_ = s.cache.Set(c, key, raw, 300*time.Second).Err()
|
||||
cancel()
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
func (s *Server) authenticate(w http.ResponseWriter, r *http.Request) (User, []byte, bool) {
|
||||
parts := strings.Fields(r.Header.Get("Authorization"))
|
||||
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
|
||||
unauthorized(w, "Bearer")
|
||||
return User{}, nil, false
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil || len(raw) != 32 {
|
||||
unauthorized(w, "Bearer")
|
||||
return User{}, nil, false
|
||||
}
|
||||
digest := sha256.Sum256([]byte(parts[1]))
|
||||
var uid string
|
||||
err = s.db.QueryRow(r.Context(), "SELECT user_id::text FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp()", digest[:]).Scan(&uid)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
unauthorized(w, "Bearer")
|
||||
return User{}, nil, false
|
||||
}
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return User{}, nil, false
|
||||
}
|
||||
u, err := s.profile(r.Context(), uid)
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return User{}, nil, false
|
||||
}
|
||||
return u, digest[:], true
|
||||
}
|
||||
|
||||
type recorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *recorder) WriteHeader(status int) { w.status = status; w.ResponseWriter.WriteHeader(status) }
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
ctxSpan, span := telemetry.Start(telemetry.Incoming(r), "http.request", trace.SpanKindServer)
|
||||
r = r.WithContext(ctxSpan)
|
||||
defer span.End()
|
||||
out := &recorder{w, 200}
|
||||
w = out
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("X-Request-Id", uuid())
|
||||
w.Header().Set("X-Instance-Id", s.instance)
|
||||
budget := 3 * time.Second
|
||||
if strings.Contains(r.URL.Path, "attachments") {
|
||||
budget = 30 * time.Second
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), budget)
|
||||
defer cancel()
|
||||
r = r.WithContext(ctx)
|
||||
if span.SpanContext().IsValid() {
|
||||
w.Header().Set("X-Trace-Id", telemetry.TraceID(ctx))
|
||||
}
|
||||
route := routeTemplate(r.URL.Path)
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
fail(w, 500, "internal_error", "Internal server error")
|
||||
}
|
||||
span.SetName(r.Method + " " + route)
|
||||
span.SetAttributes(attribute.String("http.request.method", r.Method), attribute.String("http.route", route), attribute.Int("http.response.status_code", out.status))
|
||||
if out.status >= 500 {
|
||||
span.SetStatus(codes.Error, "HTTP 5xx")
|
||||
}
|
||||
telemetry.HTTP(ctx, r.Method, route, out.status, time.Since(start).Seconds())
|
||||
if s.log != nil {
|
||||
s.log.InfoContext(ctx, "request", "method", r.Method, "route", route, "status", out.status, "duration_us", time.Since(start).Microseconds(), "request_id", w.Header().Get("X-Request-Id"))
|
||||
}
|
||||
}()
|
||||
if r.Method == "GET" && (r.URL.Path == "/health/live" || r.URL.Path == "/health/ready") {
|
||||
if r.URL.Path == "/health/ready" && (s.stopping.Load() || s.db.Ping(ctx) != nil || (s.objects != nil && !s.objects.Ready(ctx))) {
|
||||
unavailable(w)
|
||||
} else {
|
||||
reply(w, 200, map[string]string{"status": "ok"})
|
||||
}
|
||||
return
|
||||
}
|
||||
if s.stopping.Load() {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
if r.Method == "POST" && r.URL.Path == "/api/v1/users" {
|
||||
s.createUser(w, r)
|
||||
return
|
||||
}
|
||||
if r.Method == "POST" && r.URL.Path == "/api/v1/auth/sessions" {
|
||||
s.login(w, r)
|
||||
return
|
||||
}
|
||||
user, digest, ok := s.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if r.Method == "DELETE" && r.URL.Path == "/api/v1/auth/sessions/current" {
|
||||
tag, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", digest)
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
} else if tag.RowsAffected() == 0 {
|
||||
unauthorized(w, "Bearer")
|
||||
} else {
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
return
|
||||
}
|
||||
if r.Method == "GET" && r.URL.Path == "/api/v1/users/me" {
|
||||
reply(w, 200, user)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/chats" {
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.createChat(w, r, user.ID)
|
||||
case "GET":
|
||||
s.listChats(w, r, user.ID)
|
||||
default:
|
||||
missing(w)
|
||||
}
|
||||
return
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/")
|
||||
if len(parts) >= 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && s.objects != nil {
|
||||
s.serveAttachment(w, r, user.ID, parts)
|
||||
return
|
||||
}
|
||||
if len(parts) < 4 || len(parts) > 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "chats" {
|
||||
missing(w)
|
||||
return
|
||||
}
|
||||
cid := strings.ToLower(parts[3])
|
||||
if !uuidRE.MatchString(cid) {
|
||||
bad(w)
|
||||
return
|
||||
}
|
||||
chat, err := s.getChat(ctx, cid, user.ID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
missing(w)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
if len(parts) == 4 && r.Method == "GET" {
|
||||
reply(w, 200, chat)
|
||||
return
|
||||
}
|
||||
if len(parts) == 5 && parts[4] == "attachments" && r.Method == "POST" && s.objects != nil {
|
||||
s.uploadAttachment(w, r, user.ID, cid)
|
||||
return
|
||||
}
|
||||
if len(parts) == 5 && parts[4] == "messages" {
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.createMessage(w, r, user.ID, cid)
|
||||
case "GET":
|
||||
s.listMessages(w, r, cid)
|
||||
default:
|
||||
missing(w)
|
||||
}
|
||||
return
|
||||
}
|
||||
missing(w)
|
||||
}
|
||||
func (s *Server) createUser(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if !decode(w, r, &input, "username", "display_name", "password") {
|
||||
return
|
||||
}
|
||||
if !usernameRE.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validText(input.Password, 128) || utf8.RuneCountInString(input.Password) < 12 {
|
||||
bad(w)
|
||||
return
|
||||
}
|
||||
if !s.acquireKDF(r.Context(), w) {
|
||||
return
|
||||
}
|
||||
if !s.admitAuth(w, r, input.Username) {
|
||||
return
|
||||
}
|
||||
hash := hashPassword(input.Password)
|
||||
<-s.kdf
|
||||
u, err := scanUser(s.db.QueryRow(r.Context(), "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4) RETURNING "+userColumns, uuid(), input.Username, input.DisplayName, hash))
|
||||
var pgerr *pgconn.PgError
|
||||
if errors.As(err, &pgerr) && pgerr.Code == "23505" {
|
||||
fail(w, 409, "conflict", "Username already exists")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
reply(w, 201, u)
|
||||
}
|
||||
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1))
|
||||
if err != nil || len(body) != 0 {
|
||||
bad(w)
|
||||
return
|
||||
}
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok || !usernameRE.MatchString(username) || !validText(password, 128) || utf8.RuneCountInString(password) < 12 {
|
||||
unauthorized(w, "Basic")
|
||||
return
|
||||
}
|
||||
if !s.admitAuth(w, r, username) {
|
||||
return
|
||||
}
|
||||
var u User
|
||||
var hash string
|
||||
var t time.Time
|
||||
err = s.db.QueryRow(r.Context(), "SELECT "+userColumns+", password_hash FROM users WHERE username=$1", username).Scan(&u.ID, &u.Username, &u.DisplayName, &t, &hash)
|
||||
absent := errors.Is(err, pgx.ErrNoRows)
|
||||
if err != nil && !absent {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
if absent {
|
||||
hash = s.dummyHash
|
||||
}
|
||||
if !s.acquireKDF(r.Context(), w) {
|
||||
return
|
||||
}
|
||||
valid := verifyPassword(password, hash)
|
||||
if valid && !absent && needsRehash(hash) {
|
||||
replacement := hashPassword(password)
|
||||
_, err = s.db.Exec(r.Context(), "UPDATE users SET password_hash=$1 WHERE id=$2 AND password_hash=$3", replacement, u.ID, hash)
|
||||
if err != nil {
|
||||
<-s.kdf
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
<-s.kdf
|
||||
if !valid || absent {
|
||||
unauthorized(w, "Basic")
|
||||
return
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, err = rand.Read(raw); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
var expires time.Time
|
||||
err = s.db.QueryRow(r.Context(), "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,clock_timestamp()+make_interval(secs=>$3)) RETURNING expires_at", digest[:], u.ID, s.ttl).Scan(&expires)
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
u.CreatedAt = stamp(t)
|
||||
reply(w, 201, map[string]any{"token": token, "token_type": "Bearer", "expires_at": stamp(expires), "user": u})
|
||||
}
|
||||
func (s *Server) createChat(w http.ResponseWriter, r *http.Request, uid string) {
|
||||
var input struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if !decode(w, r, &input, "title", "member_ids") {
|
||||
return
|
||||
}
|
||||
if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
|
||||
bad(w)
|
||||
return
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for i, id := range input.MemberIDs {
|
||||
id = strings.ToLower(id)
|
||||
if !uuidRE.MatchString(id) || seen[id] {
|
||||
bad(w)
|
||||
return
|
||||
}
|
||||
seen[id] = true
|
||||
input.MemberIDs[i] = id
|
||||
}
|
||||
if !seen[uid] {
|
||||
bad(w)
|
||||
return
|
||||
}
|
||||
tx, err := s.db.Begin(r.Context())
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
chat := Chat{ID: uuid(), Title: input.Title, MemberIDs: input.MemberIDs}
|
||||
var t time.Time
|
||||
err = tx.QueryRow(r.Context(), "INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at", chat.ID, chat.Title).Scan(&t)
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
for _, id := range input.MemberIDs {
|
||||
_, err = tx.Exec(r.Context(), "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", chat.ID, id)
|
||||
var pgerr *pgconn.PgError
|
||||
if errors.As(err, &pgerr) && pgerr.Code == "23503" {
|
||||
bad(w)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
if tx.Commit(r.Context()) != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
chat.CreatedAt = stamp(t)
|
||||
reply(w, 201, chat)
|
||||
}
|
||||
|
||||
const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.user_id)`
|
||||
|
||||
func scanChat(row scanner) (Chat, error) {
|
||||
var c Chat
|
||||
var t time.Time
|
||||
err := row.Scan(&c.ID, &c.Title, &t, &c.MemberIDs)
|
||||
c.CreatedAt = stamp(t)
|
||||
return c, err
|
||||
}
|
||||
func (s *Server) getChat(ctx context.Context, cid, uid string) (Chat, error) {
|
||||
return scanChat(s.db.QueryRow(ctx, "SELECT "+chatColumns+" FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$2 WHERE c.id=$1", cid, uid))
|
||||
}
|
||||
|
||||
var idempotencyRE = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (s *Server) createMessage(w http.ResponseWriter, r *http.Request, uid, cid string) {
|
||||
text, attachments, ok := parseMessage(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
input := struct {
|
||||
Text string `json:"text"`
|
||||
Attachments []string `json:"attachment_ids"`
|
||||
}{text, attachments}
|
||||
keys := r.Header.Values("Idempotency-Key")
|
||||
if len(keys) != 1 || !idempotencyRE.MatchString(keys[0]) {
|
||||
bad(w)
|
||||
return
|
||||
}
|
||||
body, _ := json.Marshal(input)
|
||||
digest := sha256.Sum256(body)
|
||||
ctx := r.Context()
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
// Serialize only the same scope/key, across processes. Hash collisions only
|
||||
// serialize unrelated requests; the full unique key still decides identity.
|
||||
_, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", uid+":"+cid+":"+keys[0])
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
var previous, saved []byte
|
||||
err = tx.QueryRow(ctx, "SELECT body_hash,response FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3 AND expires_at>clock_timestamp()", uid, cid, keys[0]).Scan(&previous, &saved)
|
||||
if err == nil {
|
||||
if !bytes.Equal(previous, digest[:]) {
|
||||
fail(w, 409, "conflict", "Key already used with another message")
|
||||
return
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(201)
|
||||
_, _ = w.Write(saved)
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
// A row lock prevents cleanup of an attachment while a message links it.
|
||||
for _, id := range attachments {
|
||||
var found, status string
|
||||
err = tx.QueryRow(ctx, "SELECT id::text,status FROM attachments WHERE id=$1 AND chat_id=$2 FOR SHARE", id, cid).Scan(&found, &status)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
missing(w)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
if status == "failed" {
|
||||
fail(w, 409, "conflict", "Attachment processing failed")
|
||||
return
|
||||
}
|
||||
}
|
||||
var t time.Time
|
||||
err = tx.QueryRow(ctx, "UPDATE chats SET last_message_at=GREATEST(clock_timestamp(),last_message_at+interval '1 microsecond') WHERE id=$1 RETURNING last_message_at", cid).Scan(&t)
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
m, err := scanMessage(tx.QueryRow(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5) RETURNING id::text,chat_id::text,sender_id::text,text,created_at", uuid(), cid, uid, input.Text, t))
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
m.AttachmentIDs = attachments
|
||||
for i, id := range attachments {
|
||||
if _, err = tx.Exec(ctx, "INSERT INTO message_attachments(message_id,attachment_id,position) VALUES($1,$2,$3)", m.ID, id, i); err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
response, _ := json.Marshal(m)
|
||||
_, err = tx.Exec(ctx, `INSERT INTO message_requests(user_id,chat_id,key,body_hash,response,expires_at) VALUES($1,$2,$3,$4,$5,clock_timestamp()+interval '24 hours') ON CONFLICT(user_id,chat_id,key) DO UPDATE SET body_hash=EXCLUDED.body_hash,response=EXCLUDED.response,expires_at=EXCLUDED.expires_at`, uid, cid, keys[0], digest[:], response)
|
||||
if err != nil || tx.Commit(ctx) != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
reply(w, 201, m)
|
||||
}
|
||||
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, cid string) {
|
||||
scope := "messages:" + cid
|
||||
limit, c, ok := s.pagination(w, r, scope)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
query := `SELECT id::text,chat_id::text,sender_id::text,text,created_at,ARRAY(SELECT attachment_id::text FROM message_attachments ma WHERE ma.message_id=messages.id ORDER BY position) FROM messages WHERE chat_id=$1`
|
||||
args := []any{cid}
|
||||
if c.ID != "" {
|
||||
query += ` AND (created_at,id)>($2::timestamptz,$3::uuid)`
|
||||
args = append(args, c.Time, c.ID)
|
||||
}
|
||||
query += fmt.Sprintf(" ORDER BY messages.created_at,messages.id LIMIT $%d", len(args)+1)
|
||||
args = append(args, limit+1)
|
||||
rows, err := s.db.Query(r.Context(), query, args...)
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Message{}
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
var created time.Time
|
||||
err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &created, &m.AttachmentIDs)
|
||||
m.CreatedAt = stamp(created)
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
items = append(items, m)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
var next *string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID})
|
||||
}
|
||||
reply(w, 200, Page[Message]{items, next})
|
||||
}
|
||||
func (s *Server) listChats(w http.ResponseWriter, r *http.Request, uid string) {
|
||||
scope := "chats:" + uid
|
||||
limit, c, ok := s.pagination(w, r, scope)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
query := "SELECT " + chatColumns + " FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$1"
|
||||
args := []any{uid}
|
||||
if c.ID != "" {
|
||||
query += " WHERE (c.created_at,c.id)>($2::timestamptz,$3::uuid)"
|
||||
args = append(args, c.Time, c.ID)
|
||||
}
|
||||
query += fmt.Sprintf(" ORDER BY c.created_at,c.id LIMIT $%d", len(args)+1)
|
||||
args = append(args, limit+1)
|
||||
rows, err := s.db.Query(r.Context(), query, args...)
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Chat{}
|
||||
for rows.Next() {
|
||||
chat, err := scanChat(rows)
|
||||
if err != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
items = append(items, chat)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
unavailable(w)
|
||||
return
|
||||
}
|
||||
var next *string
|
||||
if len(items) > limit {
|
||||
items = items[:limit]
|
||||
last := items[limit-1]
|
||||
next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID})
|
||||
}
|
||||
reply(w, 200, Page[Chat]{items, next})
|
||||
}
|
||||
|
||||
// Classify before authentication/SQL so failures retain the endpoint template.
|
||||
func routeTemplate(path string) string {
|
||||
switch path {
|
||||
case "/health/live", "/health/ready":
|
||||
return path
|
||||
}
|
||||
if !strings.HasPrefix(path, "/api/v1/") {
|
||||
return "unknown"
|
||||
}
|
||||
tail := strings.TrimPrefix(path, "/api/v1")
|
||||
switch tail {
|
||||
case "/users", "/users/me", "/auth/sessions", "/auth/sessions/current", "/chats":
|
||||
return tail
|
||||
}
|
||||
p := strings.Split(strings.TrimPrefix(tail, "/"), "/")
|
||||
if len(p) == 2 && p[0] == "chats" {
|
||||
return "/chats/{id}"
|
||||
}
|
||||
if len(p) == 3 && p[0] == "chats" {
|
||||
switch p[2] {
|
||||
case "messages":
|
||||
return "/chats/{id}/messages"
|
||||
case "attachments":
|
||||
return "/chats/{id}/attachments"
|
||||
}
|
||||
}
|
||||
if len(p) == 2 && p[0] == "attachments" {
|
||||
return "/attachments/{id}"
|
||||
}
|
||||
if len(p) == 3 && p[0] == "attachments" && p[2] == "content" {
|
||||
return "/attachments/{id}/content"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/disintegration/imaging"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"math"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type Variant struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
Size int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
func fitDimensions(w, h, max int) (int, int) {
|
||||
scale := math.Min(1, math.Min(float64(max)/float64(w), float64(max)/float64(h)))
|
||||
return int(math.Max(1, math.Floor(float64(w)*scale))), int(math.Max(1, math.Floor(float64(h)*scale)))
|
||||
}
|
||||
|
||||
// Runs in a disposable child process, killed by the parent's 20s deadline.
|
||||
// The only paths are server-generated temp paths. No client arguments/shell.
|
||||
func Transform(input, dir string, versions ...int) error {
|
||||
version := 1
|
||||
if len(versions) > 0 {
|
||||
version = versions[0]
|
||||
}
|
||||
if version < 1 || version > 2 {
|
||||
return fmt.Errorf("unknown pipeline version")
|
||||
}
|
||||
quality, webpQuality := 85, "80"
|
||||
if version == 2 {
|
||||
quality, webpQuality = 90, "82"
|
||||
}
|
||||
f, e := os.Open(input)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
c, format, e := image.DecodeConfig(f)
|
||||
f.Close()
|
||||
if e != nil || c.Width < 1 || c.Height < 1 || int64(c.Width)*int64(c.Height) > maxPixels {
|
||||
return ErrInvalidImage
|
||||
}
|
||||
img, e := imaging.Open(input, imaging.AutoOrientation(true))
|
||||
if e != nil {
|
||||
return ErrInvalidImage
|
||||
}
|
||||
var oriented image.Image = img
|
||||
if format == "png" {
|
||||
oriented = orientPNG(img, pngOrientation(input))
|
||||
}
|
||||
bounds := oriented.Bounds()
|
||||
white := image.NewNRGBA(bounds)
|
||||
draw.Draw(white, bounds, &image.Uniform{C: color.White}, image.Point{}, draw.Src)
|
||||
draw.Draw(white, bounds, oriented, bounds.Min, draw.Over)
|
||||
w, h := fitDimensions(bounds.Dx(), bounds.Dy(), 256)
|
||||
thumbnail := imaging.Resize(white, w, h, imaging.Lanczos)
|
||||
crop := imaging.Fill(white, 128, 128, imaging.Center, imaging.Lanczos)
|
||||
for name, result := range map[string]image.Image{"thumbnail": thumbnail, "crop": crop} {
|
||||
f, e := os.Create(filepath.Join(dir, name))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
e = jpeg.Encode(f, result, &jpeg.Options{Quality: quality})
|
||||
ce := f.Close()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if ce != nil {
|
||||
return ce
|
||||
}
|
||||
}
|
||||
ow, oh := fitDimensions(bounds.Dx(), bounds.Dy(), 1280)
|
||||
optimized := imaging.Resize(white, ow, oh, imaging.Lanczos)
|
||||
p := filepath.Join(dir, "optimized.png")
|
||||
f, e = os.Create(p)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
e = png.Encode(f, optimized)
|
||||
f.Close()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
// Decoding/re-encoding removes EXIF and other source metadata. WebP quality 80.
|
||||
cmd := exec.Command("cwebp", "-quiet", "-q", webpQuality, "-m", "4", "-metadata", "none", p, "-o", filepath.Join(dir, "optimized"))
|
||||
if e = cmd.Run(); e != nil {
|
||||
return fmt.Errorf("webp_encode")
|
||||
}
|
||||
result := []Variant{{Name: "thumbnail", ContentType: "image/jpeg", Width: w, Height: h}, {Name: "crop", ContentType: "image/jpeg", Width: 128, Height: 128}, {Name: "optimized", ContentType: "image/webp", Width: ow, Height: oh}}
|
||||
b, _ := json.Marshal(result)
|
||||
return os.WriteFile(filepath.Join(dir, "variants.json"), b, 0600)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os/exec"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTransformFailureClassification(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
command string
|
||||
invalid bool
|
||||
}{{"exit 65", true}, {"exit 2", false}, {"kill -KILL $$", false}} {
|
||||
e := exec.Command("sh", "-c", c.command).Run()
|
||||
if errors.Is(classifyTransformFailure(nil, e), ErrInvalidImage) != c.invalid {
|
||||
t.Fatalf("misclassified encoder termination %q", c.command)
|
||||
}
|
||||
}
|
||||
if !errors.Is(classifyTransformFailure(context.DeadlineExceeded, nil), context.DeadlineExceeded) {
|
||||
t.Fatal("deadline lost")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFitFloorNoUpscale(t *testing.T) {
|
||||
for _, v := range [][5]int{{320, 200, 256, 256, 160}, {3, 2, 256, 3, 2}, {301, 200, 256, 256, 170}, {1, 40000, 256, 1, 256}} {
|
||||
w, h := fitDimensions(v[0], v[1], v[2])
|
||||
if w != v[3] || h != v[4] {
|
||||
t.Fatalf("fit %v got %dx%d", v, w, h)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestTransformAlphaAndEXIF(t *testing.T) {
|
||||
if _, e := exec.LookPath("cwebp"); e != nil {
|
||||
t.Skip("cwebp provided by Docker test target")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
input := filepath.Join(dir, "input.png")
|
||||
f, _ := os.Create(input)
|
||||
png.Encode(f, image.NewNRGBA(image.Rect(0, 0, 320, 200)))
|
||||
f.Close()
|
||||
if e := Transform(input, dir); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
b, _ := os.ReadFile(filepath.Join(dir, "thumbnail"))
|
||||
img, e := jpeg.Decode(bytes.NewReader(b))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
r, g, bl, _ := img.At(20, 20).RGBA()
|
||||
if r < 65000 || g < 65000 || bl < 65000 {
|
||||
t.Fatal("alpha not composited white")
|
||||
}
|
||||
if img.Bounds().Dx() != 256 || img.Bounds().Dy() != 160 {
|
||||
t.Fatal(img.Bounds())
|
||||
}
|
||||
source := image.NewNRGBA(image.Rect(0, 0, 320, 200))
|
||||
source.Set(0, 0, color.White)
|
||||
var jpg bytes.Buffer
|
||||
jpeg.Encode(&jpg, source, nil)
|
||||
// APP1 Exif, little endian TIFF, orientation=6 (90 degrees clockwise).
|
||||
exif := []byte{'E', 'x', 'i', 'f', 0, 0, 'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0}
|
||||
var oriented bytes.Buffer
|
||||
oriented.Write(jpg.Bytes()[:2])
|
||||
oriented.Write([]byte{255, 225})
|
||||
binary.Write(&oriented, binary.BigEndian, uint16(len(exif)+2))
|
||||
oriented.Write(exif)
|
||||
oriented.Write(jpg.Bytes()[2:])
|
||||
os.WriteFile(input, oriented.Bytes(), 0600)
|
||||
if e = Transform(input, dir); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
b, _ = os.ReadFile(filepath.Join(dir, "thumbnail"))
|
||||
img, e = jpeg.Decode(bytes.NewReader(b))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if img.Bounds().Dx() != 160 || img.Bounds().Dy() != 256 {
|
||||
t.Fatalf("EXIF ignored: %v", img.Bounds())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPNGEXIFAndMalformedIFD(t *testing.T) {
|
||||
tiff := []byte{'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0}
|
||||
if tiffOrientation(tiff) != 6 {
|
||||
t.Fatal("TIFF orientation")
|
||||
}
|
||||
for i := 0; i < len(tiff); i++ {
|
||||
_ = tiffOrientation(tiff[:i])
|
||||
}
|
||||
bad := append([]byte{}, tiff...)
|
||||
for i := 4; i < 8; i++ {
|
||||
bad[i] = 255
|
||||
}
|
||||
if tiffOrientation(bad) != 1 {
|
||||
t.Fatal("bad IFD offset")
|
||||
}
|
||||
var raw bytes.Buffer
|
||||
png.Encode(&raw, image.NewNRGBA(image.Rect(0, 0, 320, 200)))
|
||||
var chunk bytes.Buffer
|
||||
binary.Write(&chunk, binary.BigEndian, uint32(len(tiff)))
|
||||
chunk.WriteString("eXIf")
|
||||
chunk.Write(tiff)
|
||||
binary.Write(&chunk, binary.BigEndian, crc32.ChecksumIEEE(chunk.Bytes()[4:]))
|
||||
data := append(append(append([]byte{}, raw.Bytes()[:33]...), chunk.Bytes()...), raw.Bytes()[33:]...)
|
||||
dir := t.TempDir()
|
||||
input := filepath.Join(dir, "input.png")
|
||||
os.WriteFile(input, data, 0600)
|
||||
if pngOrientation(input) != 6 {
|
||||
t.Fatal("PNG eXIf orientation")
|
||||
}
|
||||
if _, e := exec.LookPath("cwebp"); e != nil {
|
||||
return
|
||||
}
|
||||
if e := Transform(input, dir); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
b, _ := os.ReadFile(filepath.Join(dir, "thumbnail"))
|
||||
img, e := jpeg.Decode(bytes.NewReader(b))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if img.Bounds().Dx() != 160 || img.Bounds().Dy() != 256 {
|
||||
t.Fatal("PNG orientation not applied", img.Bounds())
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user