Author SHA1 Message Date
MacBook b962fa0d5d Лабораторная 7 2026-11-24 12:20:21 +03:00
99 changed files with 11329 additions and 107 deletions
+10 -34
View File
@@ -1,41 +1,17 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env. # LOCAL configuration. No credential values; init-local creates all secret files.
# These are logical interface suggestions; map actual framework names in REPORT.md. APP_PORT=8443
GRAFANA_PORT=13007
BAO_PORT=18200
APP_HOST=0.0.0.0 APP_HOST=0.0.0.0
APP_PORT=8080
APP_ENV=lab APP_ENV=lab
SESSION_TTL_SECONDS=3600 SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values.
DATABASE_URL_FILE=/run/secrets/database_url
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
API_REPLICAS=2
IDEMPOTENCY_TTL_SECONDS=86400 IDEMPOTENCY_TTL_SECONDS=86400
S3_ENDPOINT=https://s3:9000 DB_TIMEOUT_MS=3000
S3_REGION=us-east-1 DB_MAX_CONNS=10
S3_BUCKET=messenger-attachments WORKER_CONCURRENCY=1
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000
BROKER_URL_FILE=/run/secrets/broker_url
WORKER_CONCURRENCY=2
JOB_MAX_ATTEMPTS=5 JOB_MAX_ATTEMPTS=5
JOB_TIMEOUT_SECONDS=60 JOB_TIMEOUT_SECONDS=60
STAGING_RETENTION_SECONDS=86400 STAGING_RETENTION_SECONDS=86400
OTEL_SERVICE_NAME=messenger-api CLEANUP_GRACE_SECONDS=3600
# Worker must set a distinct service.name. # Fixed Argon2id policy in password.go: 19456 KiB,t2,p1, salt16,hash32.
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318 # TLS CA/leaf paths and Bao roles are assigned per service in compose.yaml.
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix.
PUBLIC_BASE_URL=https://localhost:8443
TLS_CA_FILE=/run/secrets/ca.crt
TLS_CERT_FILE=/run/secrets/service.crt
TLS_KEY_FILE=/run/secrets/service.key
BAO_ADDR=https://openbao:8200
BAO_CACERT=/run/secrets/bao-ca.crt
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
ARGON2_MEMORY_KIB=19456
ARGON2_ITERATIONS=2
ARGON2_PARALLELISM=1
+55 -14
View File
@@ -1,18 +1,59 @@
## Лабораторная7 ## Лабораторная7
Автор / группа: TODO Автор/группа: **Меркулова М.А. / БВТ2303**. Цель: **4**, трек5 не заявлен.
Целевая оценка (3/4/5): TODO
Трек 5, если заявлен: TODO
Что реализовано и что перенесено: TODO ### Что реализовано
Команды запуска из чистого clone: TODO
Результаты проверок и ссылка на REPORT.md: TODO
Ограничения / известные ошибки: TODO
Источники и использование ИИ: TODO
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. Сохранена собственная lab6 (Go API×2, PG, Redis sessions, MinIO, outbox/broker/worker,
- [ ] Контракт и публичные тесты не ослаблены. OpenTelemetry/Grafana). Внешний HTTPS, native API mTLS с LB SAN; TLS verify-full DB;
- [ ] make check и make test выполнены; приложен реальный вывод. mTLS broker и Collector с раздельными identities и SAN/command restrictions.
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. Остальные сетевые зависимости защищены проверяемыми TLS-sidecar boundaries с
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. закрытым loopback hop. OpenBao non-dev persistent, exact-leaf cert auth, scoped KV
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. policies, короткий token TTL и fail-closed lease. Argon2id + реальный scrypt rehash,
общий login rate limit, ACL/logout/expiry, rotation DB secret и leaf без build,
отзыв старых credentials на новых соединениях. Runtime hardening, threat model,
trust matrix и реальный dependency/image scan с triage.
### Запуск
```sh
sh scripts/start.sh
export BASE_URL=https://localhost:8443
export CA_FILE="$PWD/secrets/public/ca.crt"
make check
make test
make test-security
python3 student-tests/verify_tls.py
python3 student-tests/verify_security.py
python3 student-tests/verify_observability.py
python3 student-tests/verify_lifecycle.py
python3 student-tests/verify_resilience.py
```
OpenBao init/unseal — явная operator процедура. Root token/unseal/CA key не
монтируются в app. Grafana https://localhost:13007, admin password — local secret.
### Доказательства
- [Отчёт](../REPORT.md)
- [Результаты](../evidence/lab7-results.md)
- [Матрица доверия](../contracts/trust-matrix.md)
- [Модель угроз](../infra/security/threat-model.md)
- [TLS/mTLS и Bao allow/deny](../evidence/tls-matrix-grade4.json)
- [ACL/Argon/rehash/rate limit](../evidence/security-grade4.json)
- [Ротация и sealed lease](../evidence/lifecycle-grade4.json)
- [Scan triage](../infra/security/scan-triage.md)
- [Сохранность/HTTPS failover](../evidence/resilience.json)
### Ограничения
Один host, нет HA. Leaf renewal/operator unseal явные; учебный Shamir1/1 требует
защищённого хранения operator material. Scoped KV credentials статичны между
ротациями. Остаточные scan findings разобраны; zero-CVE не заявляется. Трек5 и
production security гарантии не заявляются. Помощь Codex описана в REPORT.
- [x] README/COURSE/Makefile/OpenAPI/public tests сохранены.
- [x] Требуемая trust matrix заполнена.
- [x] TLS verification не отключается, прямые plaintext обходы закрыты.
- [x] Root/unseal/private keys отсутствуют в Git и app images.
- [x] Отрицательные тесты, ротация, сохранность и scan воспроизведены.
+15
View File
@@ -0,0 +1,15 @@
FROM golang:1.26.11-alpine3.23@sha256:23f198931d4bd83b4f5a613bd75656257ae8bf832dcbc2db80e1050b5219ca2a AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY cmd/ ./cmd/
COPY internal/ ./internal/
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /messenger ./cmd/messenger
FROM scratch
COPY --from=build /messenger /messenger
USER 65532:65532
ENV APP_HOST=0.0.0.0 APP_PORT=8080
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 CMD ["/messenger", "healthcheck"]
ENTRYPOINT ["/messenger"]
+213 -24
View File
@@ -1,37 +1,226 @@
# Отчёт — лабораторная 7 # Лабораторная7 — безопасность, mTLS и OpenBao
- Автор, группа: TODO Автор: **Меркулова М.А., БВТ2303**. Цель: **4**, трек5 не заявлен.
- Целевая оценка; выбранный трек 5, если нужен: TODO Ветка `solution/BVT2303-Merkulova` создана от main skeleton lab7. Основа —
- Commit/PR: TODO после публикации собственная lab6. README/COURSE/Makefile/OpenAPI/public tests не изменены;
- Использованные источники, библиотеки и помощь ИИ: TODO обязательная contracts/trust-matrix.md заполнена. Использована помощь Codex
при реализации, анализе и проверках; работоспособность проверяется реальным стендом.
## Запуск из чистого clone ## Запуск с нуля
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. Docker Desktop/Linux containers, Compose2.22+/BuildKit, Python3.9+, OpenSSL, make;
интернет для registry/Go modules/PyPI/GitHub. Windows: WSL2 + Docker integration,
не native PowerShell. Репозиторий в WSL2 лучше хранить в Linux filesystem, чтобы сохранялись Unix permissions. Все secret/CA/leaf создаются локально, ничего из lab6 не нужно.
## Архитектура и решения ```sh
cd mtusi2026lab7
sh scripts/start.sh
export BASE_URL=https://localhost:8443
export CA_FILE="$PWD/secrets/public/ca.crt"
make check
make test
make test-security
```
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. `start.sh` запускает init-local → OpenBao → явный operator init/unseal/configure →
общий compose up/build/wait. Это выполнение оператором с локальными правами,
а не автоматический unseal внутри серверного контейнера. Развёрнутый вручную
эквивалент: init-local.sh; compose up -d openbao; bao-operator.py wait; затем
bao-operator.py init; compose up -d --build --wait. Инициализированный persistent
Bao не переинициализируется. Init/migrate/db-grants/s3-init штатно exit0.
## Доказательства критериев API HTTPS8443. Grafana **https://localhost:13007**, admin/password из
`secrets/grafana_admin_password`. OpenBao operator HTTPS18200. Только localhost;
внутренние API/DB/S3/Redis/Collector/backends не имеют опубликованных портов.
CA certificate можно доверить браузеру/передать клиенту; private CA не передавать.
Нельзя использовать curl -k, verify=false или sslmode=disable.
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | `.env` задаёт APP_PORT/GRAFANA_PORT/BAO_PORT, DB/session/pipeline параметры;
| --- | --- | --- | --- | init-local добавляет LOCAL_UID/GID для запуска operator audit с владельцем файлов.
| Публичный smoke | make test | TODO | TODO | При другом порте BASE_URL/CA_FILE передать тестам. Grafana tests используют
| Остальные пункты уровня 3 | TODO | TODO | TODO | GRAFANA_URL (по умолчанию https://localhost:13007). OpenBao operator читает
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | BAO_PORT из .env или BAO_OPERATOR_ADDR из окружения.
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. После обычной остановки/перезапуска OpenBao он sealed. Оператор выполняет:
## Эксперименты и отказы ```sh
python3 scripts/bao-operator.py unseal
```
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. Для полного operator restart используется `scripts/restart.sh`: он перезапускает
Bao и явно выполняет unseal с локальным operator material. Volumes не удаляются.
`docker compose down` сохраняет данные; `down --volumes` — намеренный полный
сброс учебного стенда, после которого нужны новые согласованные Bao init/secrets.
Не удалять volume, пытаясь восстановить забытый unseal key.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | ## Границы доверия и архитектура
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
## Ограничения и следующие шаги ```mermaid
flowchart LR
C[Клиент с trusted CA] -->|HTTPS| LB[Nginx]
LB -->|mTLS LB SAN| A[API1 / API2]
A -->|TLS verify-full / role| PG[(PostgreSQL)]
A -->|mTLS + auth| R[(Redis sessions)]
A -->|mTLS + scoped S3| S[(MinIO)]
PG --> D[Dispatcher outbox]
D -->|mTLS producer identity| B[(Redis Streams)]
B -->|mTLS consumer identity| W[Worker + Pillow]
W -->|TLS role| PG
W -->|mTLS scoped prefixes| S
A -->|mTLS| O[Collector]
D -->|mTLS| O
W -->|mTLS| O
O -->|mTLS| T[Prometheus / Loki / Tempo]
G[Grafana HTTPS] -->|mTLS| T
A -->|TLS cert auth / scoped KV| V[OpenBao persistent]
W -->|TLS cert auth / scoped KV| V
```
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. Подробная [trust matrix](contracts/trust-matrix.md),
[модель угроз](infra/security/threat-model.md),
[PKI/transport/operator guide](infra/security/README.md).
DB native TLS; API native Go TLS with mandatory client cert and LB DNS SAN.
Для Redis/S3/telemetry применён проверяемый mTLS sidecar: native backend слушает
только loopback в общем namespace пары, отдельный TLS proxy — сетевой адрес.
Direct plaintext bypass проверяется отрицательно. Health/bootstrap local hops
ограничены этой границей; API self cert даёт только /health, не business.
У broker разные dispatcher/worker cert и Redis users, ACL команд/ключей.
Proxy дополнительно связывает AUTH/HELLO username с SAN и разрешает worker
публикацию только в invalid-envelope DLQ, а не job stream. На Collector separate
allowlist для ingest4318 и scrape8888/8889. Trusted CA без правильной SAN роли
не даёт доступа. CA/hostname проверяют все исходящие клиенты.
## Пароли, сессии и login budget
Новые пароли: Argon2id v19, **m=19456KiB,t=2,p=1**, salt16 random bytes, hash32;
PHC строка хранит параметры/salt/hash. Сравнение constant-time. Парсер ограничивает
параметры до запуска дорогой функции. Старый scrypt проверяется только с известными
ограниченными параметрами; успешный login обновляет hash на Argon2id в PostgreSQL.
Реальный legacy-row → Basic login → persisted Argon rehash проверяет verify_security.
Shared Redis Lua: общий budget **120 expensive auth/registration requests/minute**
для двух реплик, отдельный username budget10 login/minute. Ошибка429 имеет
Retry-After60; при отказе limiter нет fail-open. Username в Redis key SHA256,
не plaintext credential. Не доверяем X-Forwarded-For для выбора budget.
Два concurrent hash slots на процесс ограничивают Argon memory; по умолчанию
около38MiB на базовые два hash, без учёта остального процесса. Глобальный flood
может временно ограничить легитимный login — осознанный availability tradeoff.
На Mac AppleM4 unit benchmark10 итераций: **17.680ms/op**,19,927,106B/op.
Это измерение локальной стоимости, не обещание latency под Docker CPU throttling.
Отдельно сохранено реальное HTTPS rehash время в security-grade4.json. Worst-case
rate120/min × наблюдавшаяся стоимость оценивает бюджет, а не гарантирует CPU SLA.
TLS/DB/HTTP overhead и более дорогой legacy rehash нужно учитывать отдельно.
Bearer session keys = `session:`+SHA256(token), finite TTL, logout DEL. Token только
в ответе авторизации/памяти клиента; telemetry не содержит Authorization/пароли/body.
Чужой user и поддельный X-User-Id не обходят membership ACL. Bytes≤10MiB,
pixels≤40M; изображения полностью декодируются до принятия, worker CPU1,
RAM1536MiB, decoder RLIMIT_AS1GiB, timeout60s и tmpfs128MiB сохранены.
## OpenBao и жизненный цикл
OpenBao2.4.3, native HTTPS, **не dev-mode**, persistent file volume. Cert auth
привязан к точному leaf каждой роли + DNS SAN. Policies из infra/security/policies:
только read secret/<role>, без default broad policy. API/worker не имеют root token,
unseal shares, CA private key или общего постоянного bootstrap token.
Оператор создаёт одноразовые root/unseal данные в secrets/operator (0700/0600),
не монтирует их в сервисы. Учебный Shamir1/1 требует защиты operator backups;
production separation custodians/auto-unseal вне scope. Сервисная bootstrap identity
— ограниченный по сроку leaf7d, отдельно выданный оператором. Root CA365d.
Это initial trust, не встроенный в образ credential. Нужна operator rotation до expiry.
Сервисы получают KV secrets через cert login; token TTL60/max120s, scoped
reauthentication каждые20s. Отказ refresh не продлевает последнюю lease. После
истечения API возвращает503 (live остаётся), worker/dispatcher exit75 и новые
запуски fail-closed до восстановления Bao. Нет fallback на plaintext или файлы
приложения с прежними паролями. После unseal reauth восстанавливает работу.
```sh
python3 scripts/rotate-db-secret.py
python3 scripts/rotate-leaf.py worker
```
Первая команда меняет пароль worker DB, обновляет scoped KV и перезапускает
только worker/pool. Вторая выдаёт новый leaf, заменяет cert-auth binding,
добавляет старый serial в denylist и перезапускает caller. **Без build**.
Старые password/cert проверяются НОВЫМ соединением; существующие могут жить
до timeout, поэтому rollover drain обязателен. Старый token ограничен TTL.
## Hardening и supply chain
Runtime app/worker/proxies non-root; read_only, no-new-privileges, cap_drop ALL.
Нет privileged, host network, Docker socket. Writable named volumes только для
state; tmpfs ограничены. Init ownership helpers имеют единственную CHOWN capability
и network none; это краткоживущие operator setup, не права приложения. MinIO
stateful runtime использует ограниченный root без capabilities; rootfs read-only,
доступен только за mTLS proxy. Не заявляем, что это полная production sandbox.
Go1.26.11 и Python3.13.16 закреплены digest; Pillow13.0.0, OTel1.47/log exporter0.23,
pgx5.13; остальные runtime versions закреплены Compose. MinIO собирается из
официальных исходников RELEASE.2025-10-15T17-29-55Z с checksum. Зависимости Go
закреплены go.mod/go.sum. [Scan triage](infra/security/scan-triage.md) объясняет
применимость оставшихся находок. Zero-CVE/полный scan всех upstream images не заявлены.
```sh
python3 scripts/scan.py
```
## Проверки и доказательства
```sh
export BASE_URL=https://localhost:8443
export CA_FILE="$PWD/secrets/public/ca.crt"
make check
make test
make test-security
CGO_ENABLED=0 go test ./...
CGO_ENABLED=0 go vet ./...
python3 student-tests/verify_tls.py
python3 student-tests/verify_security.py
python3 student-tests/verify_variants.py
python3 student-tests/verify_pipeline.py
python3 student-tests/verify_observability.py
python3 student-tests/verify_lifecycle.py
python3 student-tests/verify_resilience.py
```
Сценарии остановки/ротации выполнять последовательно. verify_lifecycle изменяет
worker secret/leaf и временно seals Bao; finally unseals/restarts. Local operator
material доступен только runner этих тестов. `security_internal.py` запускается
в ephemeral audit profile, не в обычных production контейнерах.
| Требование | Проверка / evidence |
|---|---|
| HTTPS CA/hostname, полный минимум | make test/test-security; verify_security |
| mTLS API/broker/Collector, same-CA wrong identity | verify_tls → tls-matrix-grade4.json |
| Bao scoped allow/deny и ограниченный TTL | тот же TLS audit |
| Argon2id, реальный rehash, shared429, ACL/logout/expiry | verify_security → security-grade4.json |
| Worker DB/S3/broker least privilege | /messenger security-audit → least-privilege.json |
| Rotation/отзыв/expiry/sealed | verify_lifecycle → lifecycle-grade4.json |
| Сохранность/HTTPS failover | verify_resilience → resilience.json |
| Lab6 traces/logs/metrics и no leaks | verify_observability → observability-grade4.json |
| Изображения и durable pipeline | verify_variants/verify_pipeline JSON |
| Реальный scan и применимость | scan-summary.json + scan-triage.md |
Точные результаты текущего прогона: [evidence/lab7-results.md](evidence/lab7-results.md).
## Ограничения и источники
Один Docker-host и одиночные хранилища; host/root/operator compromise и HA вне scope.
Ротация leaf/operator CA не является исследовательским треком5, CA rollover не
реализован. Leaf renewal — явная operator процедура. Scoped KV credentials статичны
между ротациями; bounded Bao lease управляет допустимостью их использования.
Нагрузочные и production security гарантии не заявляются. Windows отдельно не тестировался.
Источники: собственная lab6; [OpenBao cert auth](https://openbao.org/docs/auth/cert/),
[OpenBao policies](https://openbao.org/docs/concepts/policies/),
[OWASP Argon2id](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html),
[Go release security fixes](https://go.dev/doc/devel/release),
[Trivy](https://trivy.dev/docs/), [Pillow](https://pillow.readthedocs.io/).
Runtime secret bind files have mode0444 inside mounts so non-root Linux UIDs can read them. The enclosing host secrets directory stays0700; operator CA key/root token/unseal file stay0600 and are never runtime mounts. Each container receives only its own named files/leaf directory.
Redis sessions: отдельный user api ограничен session:*/login:* и GET/SET/DEL/INCR/EXPIRE/EVAL; CONFIG/FLUSHALL/чужие prefixes не разрешены. Operator health/expiry использует отдельную identity.
+431
View File
@@ -0,0 +1,431 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"crypto/tls"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/minio/minio-go/v7"
"github.com/redis/go-redis/v9"
"mtusi-messenger/internal/database"
"mtusi-messenger/internal/messenger"
"mtusi-messenger/internal/objectstore"
"mtusi-messenger/internal/pipeline"
"mtusi-messenger/internal/security"
"mtusi-messenger/internal/telemetry"
)
func env(name, fallback string) string {
if value := os.Getenv(name); value != "" {
return value
}
return fallback
}
func secret(envName, fileEnv string) (string, error) {
if value := os.Getenv(envName); value != "" {
return value, nil
}
path := os.Getenv(fileEnv)
if path == "" {
return "", fmt.Errorf("set %s or %s", envName, fileEnv)
}
b, err := os.ReadFile(path)
if err != nil {
return "", err
}
value := strings.TrimSpace(string(b))
if value == "" {
return "", fmt.Errorf("%s is empty", path)
}
return value, nil
}
func positiveInt(name string, fallback int) (int, error) {
raw := env(name, strconv.Itoa(fallback))
n, err := strconv.Atoi(raw)
if err != nil || n < 1 {
return 0, fmt.Errorf("invalid %s", name)
}
return n, nil
}
func main() {
if len(os.Args) > 1 && os.Args[1] == "memory" {
values := map[string]int64{}
for _, name := range []string{"memory.current", "memory.peak", "memory.max"} {
data, err := os.ReadFile("/sys/fs/cgroup/" + name)
if err != nil {
log.Fatal("cgroup memory metrics unavailable")
}
n, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
if err != nil {
log.Fatal("invalid cgroup metric")
}
values[name] = n
}
_ = json.NewEncoder(os.Stdout).Encode(values)
return
}
tlsConfig, tlsErr := security.ClientTLS()
if tlsErr != nil {
log.Fatal("TLS configuration unavailable")
}
http.DefaultTransport = &http.Transport{TLSClientConfig: tlsConfig}
port := env("APP_PORT", "8080")
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
client := &http.Client{Timeout: 2 * time.Second}
resp, err := client.Get("https://" + env("TLS_SERVER_NAME", "api1") + ":" + port + "/health/ready")
if err != nil || resp.StatusCode != http.StatusOK {
os.Exit(1)
}
_ = resp.Body.Close()
return
}
if e := security.LoadSecrets(context.Background()); e != nil {
log.Fatal("service authentication/secrets unavailable")
}
host := env("APP_HOST", "0.0.0.0")
if _, err := strconv.Atoi(port); err != nil {
log.Fatal("invalid APP_PORT")
}
ttlSeconds, err := positiveInt("SESSION_TTL_SECONDS", 3600)
if err != nil {
log.Fatal(err)
}
idempotencyTTLSeconds, err := positiveInt("IDEMPOTENCY_TTL_SECONDS", 86400)
if err != nil || idempotencyTTLSeconds < 86400 {
log.Fatal("IDEMPOTENCY_TTL_SECONDS must be at least 86400")
}
dbTimeoutMS, err := positiveInt("DB_TIMEOUT_MS", 3000)
if err != nil {
log.Fatal(err)
}
maxConns, err := positiveInt("DB_MAX_CONNS", 10)
if err != nil {
log.Fatal(err)
}
databaseURL, err := secret("DATABASE_URL", "DATABASE_URL_FILE")
if err != nil {
log.Fatal(err)
}
logger := log.New(os.Stdout, "", log.LstdFlags|log.LUTC)
mode := "api"
if len(os.Args) > 1 {
mode = os.Args[1]
}
if mode == "api" || mode == "worker" || mode == "dispatcher" {
service := "messenger-" + mode
if v := os.Getenv("OTEL_SERVICE_NAME"); v != "" {
service = v
}
initctx, done := context.WithTimeout(context.Background(), 3*time.Second)
shutdown, initErr := telemetry.Start(initctx, service, env("INSTANCE_ID", mode+"-1"))
done()
if initErr != nil {
log.Fatal("invalid telemetry configuration")
}
defer func() {
c, done := context.WithTimeout(context.Background(), 3*time.Second)
defer done()
_ = shutdown(c)
}()
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
config, err := pgxpool.ParseConfig(databaseURL)
if err != nil {
log.Fatal("invalid database configuration")
}
if config.ConnConfig.TLSConfig == nil || config.ConnConfig.TLSConfig.InsecureSkipVerify || config.ConnConfig.TLSConfig.ServerName == "" {
log.Fatal("database requires TLS verify-full")
}
config.ConnConfig.Tracer = telemetry.DBTracer{}
config.MaxConns = int32(maxConns)
config.ConnConfig.RuntimeParams["application_name"] = env("INSTANCE_ID", "maintenance")
config.MinConns = 1
config.MaxConnLifetime = 30 * time.Minute
var pool *pgxpool.Pool
for {
pool, err = pgxpool.NewWithConfig(ctx, config)
if err == nil {
err = pool.Ping(ctx)
}
if err == nil {
break
}
if pool != nil {
pool.Close()
}
if ctx.Err() != nil {
log.Fatal("database unavailable during startup")
}
time.Sleep(time.Second)
}
defer pool.Close()
if mode == "api" || mode == "worker" || mode == "dispatcher" {
capacity, _ := positiveInt("WORKER_CONCURRENCY", 1)
if err = telemetry.Monitor(pool, mode, capacity); err != nil {
log.Fatal("invalid telemetry instruments")
}
}
if len(os.Args) > 1 && os.Args[1] == "migrate" {
if err = database.Migrate(ctx, pool); err != nil {
log.Fatalf("migration failed: %v", err)
}
logger.Print("migrations complete")
return
}
access, err := secret("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE")
if err != nil {
log.Fatal(err)
}
secretKey, err := secret("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE")
if err != nil {
log.Fatal(err)
}
objects, err := objectstore.New(env("S3_ENDPOINT", "https://s3:9000"), env("S3_REGION", "us-east-1"), env("S3_BUCKET", "messenger-attachments"), access, secretKey)
if err != nil {
log.Fatal("invalid S3 configuration")
}
if mode == "security-audit" {
var encrypted bool
if pool.QueryRow(ctx, `SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()`).Scan(&encrypted) != nil || !encrypted {
log.Fatal("database TLS audit failed")
}
if e := pool.QueryRow(ctx, `SELECT password_hash FROM users LIMIT 1`).Scan(new(string)); e == nil {
log.Fatal("worker may read password hashes")
}
e := objects.Client.MakeBucket(ctx, "forbidden-audit-bucket", minio.MakeBucketOptions{})
if minio.ToErrorResponse(e).Code != "AccessDenied" {
log.Fatal("bucket admin privilege exposed")
}
e = objects.Put(ctx, "staging/forbidden-worker-write", strings.NewReader("audit"), 5, "text/plain")
if minio.ToErrorResponse(e).Code != "AccessDenied" {
log.Fatal("worker staging write privilege exposed")
}
url, e := secret("BROKER_URL", "BROKER_URL_FILE")
if e != nil {
log.Fatal("broker credential unavailable")
}
cfg, e := redis.ParseURL(url)
if e != nil {
log.Fatal("broker config invalid")
}
cfg.TLSConfig = tlsConfig.Clone()
b := redis.NewClient(cfg)
defer b.Close()
if b.Ping(ctx).Err() != nil {
log.Fatal("broker TLS audit failed")
}
if e = b.Do(ctx, "CONFIG", "GET", "*").Err(); e == nil {
log.Fatal("broker administration not denied")
}
fmt.Println(`{"status":"PASS","postgres_tls":true,"worker_password_table_denied":true,"s3_admin_denied":true,"staging_write_denied":true,"broker_admin_denied":true}`)
return
}
if len(os.Args) > 1 && os.Args[1] == "s3-bootstrap" {
for {
err = objects.Client.MakeBucket(ctx, objects.Bucket, minio.MakeBucketOptions{Region: env("S3_REGION", "us-east-1")})
if err == nil {
break
}
if exists, e := objects.Client.BucketExists(ctx, objects.Bucket); e == nil && exists {
break
}
if ctx.Err() != nil {
log.Fatal("S3 bootstrap unavailable")
}
time.Sleep(time.Second)
}
if err = objects.Client.SetBucketPolicy(ctx, objects.Bucket, ""); err != nil {
log.Fatal("cannot enforce private bucket")
}
data, e := os.ReadFile("/run/bootstrap/service-secrets.json")
if e != nil {
log.Fatal("bootstrap identities unavailable")
}
var roles map[string]map[string]string
if json.Unmarshal(data, &roles) != nil {
log.Fatal("invalid identity document")
}
for role, values := range roles {
if role == "migrate" {
continue
}
if err = objectstore.Bootstrap(ctx, env("S3_ENDPOINT", "https://s3:9000"), objects.Bucket, access, secretKey, values["S3_ACCESS_KEY_ID"], values["S3_SECRET_ACCESS_KEY"], role); err != nil {
log.Fatal("S3 scoped identity bootstrap failed")
}
}
logger.Print("private MinIO bucket and limited API user ready")
return
}
if len(os.Args) > 1 && (os.Args[1] == "worker" || os.Args[1] == "dispatcher" || os.Args[1] == "replay" || os.Args[1] == "failed-jobs" || os.Args[1] == "fault") {
var broker *redis.Client
if os.Args[1] == "worker" || os.Args[1] == "dispatcher" {
brokerURL, e := secret("BROKER_URL", "BROKER_URL_FILE")
if e != nil {
log.Fatal(e)
}
options, e := redis.ParseURL(brokerURL)
if e != nil {
log.Fatal("invalid broker configuration")
}
options.TLSConfig = tlsConfig.Clone()
options.DialTimeout = 2 * time.Second
options.ReadTimeout = 3 * time.Second
options.WriteTimeout = 3 * time.Second
broker = redis.NewClient(options)
defer broker.Close()
}
timeout, e := positiveInt("JOB_TIMEOUT_SECONDS", 60)
if e != nil || timeout > 120 {
log.Fatal("JOB_TIMEOUT_SECONDS must be 1..120")
}
retention, e := positiveInt("STAGING_RETENTION_SECONDS", 86400)
if e != nil {
log.Fatal(e)
}
processor := &pipeline.Pipeline{DB: pool, Broker: broker, Objects: objects, Timeout: time.Duration(timeout) * time.Second, Retention: time.Duration(retention) * time.Second, Logger: logger}
runctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
switch os.Args[1] {
case "dispatcher":
processor.Dispatch(runctx)
case "worker":
concurrency, e := positiveInt("WORKER_CONCURRENCY", 1)
if e != nil {
log.Fatal(e)
}
if e = processor.Worker(runctx, concurrency); e != nil {
log.Fatal(e)
}
default:
if e = processor.Command(ctx, os.Args[1:]); e != nil {
log.Fatal(e)
}
}
return
}
if len(os.Args) > 1 && (os.Args[1] == "cleanup" || os.Args[1] == "cleanup-loop") {
grace, err := positiveInt("CLEANUP_GRACE_SECONDS", 3600)
if err != nil || grace < 120 {
log.Fatal("CLEANUP_GRACE_SECONDS must be at least 120")
}
loopctx, stopCleanup := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stopCleanup()
for {
cleanupctx, cancelCleanup := context.WithTimeout(loopctx, 60*time.Second)
result, cleanupErr := messenger.Cleanup(cleanupctx, pool, objects, time.Duration(grace)*time.Second)
cancelCleanup()
if cleanupErr != nil {
logger.Print("cleanup failed; retained objects for next sweep")
} else {
_ = json.NewEncoder(os.Stdout).Encode(result)
}
if os.Args[1] == "cleanup" {
if cleanupErr != nil {
os.Exit(1)
}
return
}
select {
case <-loopctx.Done():
return
case <-time.After(60 * time.Second):
}
}
}
if len(os.Args) > 2 && os.Args[1] == "s3-audit" {
if err = objects.Audit(ctx, os.Args[2]); err != nil {
log.Fatal(err)
}
fmt.Println("PASS: anonymous S3 GET=403; API credentials cannot create buckets")
return
}
if len(os.Args) > 2 && os.Args[1] == "s3-stat" {
info, err := objects.Client.StatObject(ctx, objects.Bucket, os.Args[2], minio.StatObjectOptions{})
if err != nil {
if minio.ToErrorResponse(err).Code != "NoSuchKey" {
log.Fatal("S3 stat failed")
}
fmt.Println(`{"exists":false}`)
return
}
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{"exists": true, "size_bytes": info.Size})
return
}
instanceID := env("INSTANCE_ID", "")
if instanceID == "" {
log.Fatal("INSTANCE_ID is required")
}
cacheURL, err := secret("CACHE_URL", "CACHE_URL_FILE")
if err != nil {
log.Fatal(err)
}
redisOptions, err := redis.ParseURL(cacheURL)
if err != nil {
log.Fatal("invalid cache configuration")
}
redisOptions.TLSConfig = tlsConfig.Clone()
sessions := redis.NewClient(redisOptions)
sessions.AddHook(telemetry.RedisHook{})
defer sessions.Close()
for {
if err = sessions.Ping(ctx).Err(); err == nil {
break
}
if ctx.Err() != nil {
log.Fatal("session store unavailable during startup")
}
time.Sleep(time.Second)
}
for {
if err = objects.Ready(ctx); err == nil {
break
}
if ctx.Err() != nil {
log.Fatal("S3 unavailable during startup")
}
time.Sleep(time.Second)
}
dbTimeout := time.Duration(dbTimeoutMS) * time.Millisecond
srv := &http.Server{Addr: host + ":" + port, Handler: messenger.NewHandler(pool, sessions, objects, time.Duration(ttlSeconds)*time.Second, time.Duration(idempotencyTTLSeconds)*time.Second, dbTimeout, instanceID, logger), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 45 * time.Second, WriteTimeout: 60 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 32 * 1024}
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGTERM, os.Interrupt)
done := make(chan struct{})
go func() {
defer close(done)
<-stop
logger.Print("shutdown started")
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 8*time.Second)
defer shutdownCancel()
if shutdownErr := srv.Shutdown(shutdownCtx); shutdownErr != nil {
logger.Printf("shutdown error: %v", shutdownErr)
}
logger.Print("shutdown complete")
}()
logger.Printf("listening on %s", srv.Addr)
srv.TLSConfig, err = security.ServerTLS()
if err != nil {
log.Fatal("server TLS unavailable")
}
srv.TLSConfig.MinVersion = tls.VersionTLS12
if err = srv.ListenAndServeTLS("", ""); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Fatal(err)
}
<-done
}
+1257
View File
File diff suppressed because it is too large Load Diff
+47 -27
View File
@@ -1,37 +1,57 @@
# Матрица доверия — заполнить в решении lab7 # Матрица доверия — решение lab7, оценка4
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. Все сертификаты подписаны локальным operator CA `secrets/public/ca.crt`.
Private CA / root token / unseal share доступны только оператору, не монтируются
в приложение. Leaf7d; Bao token60s/max120s, reauth20s. DNS SAN проверяет роль,
CA сам по себе не выдаёт разрешение. Server hostname всегда проверяется.
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | | Связь | Реальный endpoint / защита | Identity / права | Проверка |
|---|---|---|---| |---|---|---|---|
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | | Клиент → LB | https://localhost:8443, TLS1.2+ | SAN localhost; Basic→Bearer; Redis общий login budget | make test, make test-security, verify_security |
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | | LB → API1/API2 | https://api1:8080, https://api2:8080; обязательное mTLS | server SAN messenger-api; только client SAN lb для business; self SAN только health | verify_tls: correct/no cert/foreign CA/trusted outsider для обеих реплик; rotate-leaf.py |
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | | API/worker/dispatcher/cleanup → PostgreSQL | postgres:5432 native TLS verify-full | отдельные api/worker/dispatcher/cleanup roles; worker не читает users; schema только migrate | worker security-audit, verify_lifecycle password rotation |
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO | | API/worker → S3 | https://s3:9000 mTLS sidecar → localhost:19000 | SAN allowlist; разные S3 users; API пишет staging, worker пишет originals/variants; вне prefixes denied | verify_tls + verify_variants + worker security-audit |
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | | Dispatcher/worker → broker | broker:6379 mTLS sidecar → localhost:16379 | разные SAN и Redis usernames; producer только XADD jobs, consumer ACK/read/DLQ; AUTH привязан к SAN | verify_tls no cert/foreign CA/trusted outsider/consumer publish denied; security-audit |
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO | | API/worker/dispatcher → Collector | https://otel-collector:4318 mTLS → localhost:14318 | только api1/api2/worker/dispatcher (+operator audit); prom только scrape ports | verify_tls полный набор отказов; verify_observability |
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO | | Collector → Loki/Tempo | https://loki:3100/otlp, https://tempo:4318; mTLS | SAN otel-collector; server SAN проверяется | verify_tls, сквозные stored logs/trace в verify_observability |
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO | | Prometheus → Collector | https://otel-collector:8888/8889 mTLS | SAN prometheus, только scrape listeners | verify_tls + dashboard queries |
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO | | Grafana → data sources | https://prometheus:9090, https://loki:3100, https://tempo:3200; mTLS | SAN grafana; не допускается произвольный CA client | verify_tls outsider denied; verify_observability |
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO | | Сервисы → OpenBao | https://openbao:8200 native TLS + cert auth | exact leaf binding + read-only secret/<role>; no root/default broad policy | verify_tls real allow/deny; verify_lifecycle seal/expiry |
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO | | Оператор → OpenBao/Grafana/S3 | localhost18200 HTTPS + root token; localhost13007 HTTPS + admin auth; S3 operator through internal mTLS | root/unseal только operator; S3 admin только server/bootstrap | operator scripts; audit no app admin mounts |
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO | | API → Redis sessions | redis:6379 mTLS sidecar → localhost:16379 | api1/api2 SAN + password; session keys sha256(token), finite TTL | verify_security logout; expiry test; TLS matrix |
| Replication / cluster | N/A | одиночные PG/MinIO/Redis/Bao/telemetry; нет заявленной replication | ограничения REPORT |
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. API не публикует задания прямо в broker: он фиксирует outbox; реальный producer —
dispatcher. Поэтому для этой связи проверяются dispatcher и worker, а API
проверяется как отдельная identity на Collector и DB/S3/Redis. Worker не получает
API credentials или административные DB/S3/OpenBao secrets.
## Обязательные отрицательные проверки ## Transport/proxy boundary и health/bootstrap
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». Sidecar и только его native backend используют общий network namespace. Native
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. listeners привязаны к127.0.0.1 и доступны только внутри этой пары; отдельный
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. TLS listener доступен по service alias. `verify_tls` доказывает, что direct
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. plaintext ports16379/19000/14318/19090/13100/13200 недоступны извне namespace.
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. TLS sidecar проверяет peer chain, validity, SAN allowlist и serial denylist.
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. Нет сетевого plaintext hop между контейнерами разных namespace.
## Bootstrap и эксплуатация PG native TLS: local Unix socket допускается только для operator setup/tests и
локального readiness. Redis/MinIO native health probes выполняются по loopback
в собственном namespace; Collector health13133 также loopback. API healthcheck
использует собственный leaf, разрешённый только для /health; LB monitor использует
lb cert. Никаких дополнительных публичных health/business обходов нет.
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. Bao init/unseal — явные operator HTTPS-команды. App bootstrap: временный scoped
token по exact service leaf → свой KV path → runtime memory. Leaf7d не является
постоянным embedded bootstrap secret; renewal требует operator rollover до expiry.
Миграции и S3 init выполняются одноразово операторскими identities с узким
назначением; их ключи не передаются API/worker. `db-grants` использует только
PG admin password, не весь operator directory.
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 — хорошее расширение, но не обязательное название технологии. Ротация worker DB secret и leaf выполняется без сборки образов. Старый пароль
проверяется новым TLS DB connection; старый leaf — новым mTLS broker connection.
Активные соединения могут дожить до timeout; rollover перезапускает caller для
drain. После sealing Bao последняя lease действует не дольше её срока; далее
API503, worker exit/restart fail-closed, без fallback. См. verify_lifecycle.py.
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. Redis sessions: отдельный user api ограничен session:*/login:* и GET/SET/DEL/INCR/EXPIRE/EVAL; CONFIG/FLUSHALL/чужие prefixes не разрешены. Operator health/expiry использует отдельную identity.
+27
View File
@@ -0,0 +1,27 @@
{
"status": "PASS",
"date": "2026-11-23",
"source": "isolated source copy excluding .git, .env, secrets and virtual environments",
"project": "mtusi-lab7-clean-final",
"api_port": 8444,
"grafana_port": 13008,
"bao_port": 18201,
"new_CA_and_secrets": true,
"fresh_volumes": [
"postgres_data",
"redis_data",
"minio_data",
"broker_data",
"prometheus_data",
"loki_data",
"tempo_data",
"grafana_data",
"bao_data"
],
"build_cache_used": true,
"operator_init_unseal": "PASS",
"public_https_smoke": "PASS",
"untrusted_CA_negative": "PASS",
"temporary_stack_removed": true,
"includes_limited_session_ACL": true
}
+83
View File
@@ -0,0 +1,83 @@
[
{
"attempt": 1,
"event": "job.published",
"job_id": "d5d99b1f-0bf1-455d-82d1-af0116a6fdcf",
"service.name": "messenger-dispatcher",
"severity": "INFO",
"span_id": "53ba305357fcda41",
"success": true,
"timestamp": "2026-11-23T08:31:38.490664837Z",
"trace_id": "403dab53696c4c959fae377bd070a998"
},
{
"attempt": 1,
"event": "job.started",
"job_id": "d5d99b1f-0bf1-455d-82d1-af0116a6fdcf",
"request_id": "b097a412-96c8-4495-88bc-584ba4b12f15",
"service.name": "messenger-worker",
"severity": "INFO",
"span_id": "24f17409f78091d5",
"timestamp": "2026-11-23T08:31:38.678255629Z",
"trace_id": "403dab53696c4c959fae377bd070a998"
},
{
"attempt": 2,
"event": "job.published",
"job_id": "d5d99b1f-0bf1-455d-82d1-af0116a6fdcf",
"service.name": "messenger-dispatcher",
"severity": "INFO",
"span_id": "3de7a866aedd9f7f",
"success": true,
"timestamp": "2026-11-23T08:31:43.503889673Z",
"trace_id": "403dab53696c4c959fae377bd070a998"
},
{
"attempt": 2,
"event": "job.started",
"job_id": "d5d99b1f-0bf1-455d-82d1-af0116a6fdcf",
"request_id": "b097a412-96c8-4495-88bc-584ba4b12f15",
"service.name": "messenger-worker",
"severity": "INFO",
"span_id": "9d669e86c32cb41b",
"timestamp": "2026-11-23T08:31:43.505923923Z",
"trace_id": "403dab53696c4c959fae377bd070a998"
},
{
"duration_ms": 145,
"event": "job.completed",
"job_id": "d5d99b1f-0bf1-455d-82d1-af0116a6fdcf",
"outcome": "retry",
"request_id": "b097a412-96c8-4495-88bc-584ba4b12f15",
"service.name": "messenger-worker",
"severity": "ERROR",
"span_id": "24f17409f78091d5",
"timestamp": "2026-11-23T08:31:38.820952296Z",
"trace_id": "403dab53696c4c959fae377bd070a998"
},
{
"duration_ms": 10,
"event": "http.request",
"method": "POST",
"request_id": "b097a412-96c8-4495-88bc-584ba4b12f15",
"route": "/api/v1/chats/{chat_id}/attachments",
"service.name": "messenger-api",
"severity": "INFO",
"span_id": "d912c35b8000bc05",
"status": 202,
"timestamp": "2026-11-23T08:31:38.257969879Z",
"trace_id": "403dab53696c4c959fae377bd070a998"
},
{
"duration_ms": 279,
"event": "job.completed",
"job_id": "d5d99b1f-0bf1-455d-82d1-af0116a6fdcf",
"outcome": "success",
"request_id": "b097a412-96c8-4495-88bc-584ba4b12f15",
"service.name": "messenger-worker",
"severity": "INFO",
"span_id": "9d669e86c32cb41b",
"timestamp": "2026-11-23T08:31:43.78323884Z",
"trace_id": "403dab53696c4c959fae377bd070a998"
}
]
+135
View File
@@ -0,0 +1,135 @@
{
"batches": [
{
"resource": {
"attributes": [
{
"key": "deployment.environment.name",
"value": {
"stringValue": "lab"
}
},
{
"key": "service.instance.id",
"value": {
"stringValue": "api-2"
}
},
{
"key": "service.name",
"value": {
"stringValue": "messenger-api"
}
},
{
"key": "service.version",
"value": {
"stringValue": "lab6-v1"
}
}
]
},
"scopeSpans": [
{
"scope": {
"name": "mtusi-messenger/telemetry-v1"
},
"spans": [
{
"traceId": "D3wh6gXxbWWBed22gHfojA==",
"spanId": "W/QkJVJ/2IY=",
"parentSpanId": "eG0qzJ/nc30=",
"flags": 257,
"name": "redis.get",
"kind": "SPAN_KIND_CLIENT",
"startTimeUnixNano": "1795422524752972507",
"endTimeUnixNano": "1795422524753071091",
"attributes": [
{
"key": "db.system.name",
"value": {
"stringValue": "redis"
}
},
{
"key": "db.operation.name",
"value": {
"stringValue": "get"
}
}
],
"status": {}
},
{
"traceId": "D3wh6gXxbWWBed22gHfojA==",
"spanId": "KlAQ0PHzbnY=",
"parentSpanId": "eG0qzJ/nc30=",
"flags": 257,
"name": "db.pool.acquire",
"kind": "SPAN_KIND_CLIENT",
"startTimeUnixNano": "1795422524753091132",
"endTimeUnixNano": "1795422524754625632",
"attributes": [
{
"key": "db.system.name",
"value": {
"stringValue": "postgresql"
}
},
{
"key": "error",
"value": {
"boolValue": true
}
}
],
"status": {
"message": "dependency unavailable",
"code": "STATUS_CODE_ERROR"
}
},
{
"traceId": "D3wh6gXxbWWBed22gHfojA==",
"spanId": "eG0qzJ/nc30=",
"flags": 257,
"name": "POST /api/v1/chats/{chat_id}/messages",
"kind": "SPAN_KIND_SERVER",
"startTimeUnixNano": "1795422524752965548",
"endTimeUnixNano": "1795422524754653715",
"attributes": [
{
"key": "http.route",
"value": {
"stringValue": "/api/v1/chats/{chat_id}/messages"
}
},
{
"key": "http.request.method",
"value": {
"stringValue": "POST"
}
},
{
"key": "request.id",
"value": {
"stringValue": "58f941c0-6993-4bc4-b7f2-745d049e8426"
}
},
{
"key": "http.response.status_code",
"value": {
"intValue": "503"
}
}
],
"status": {
"message": "HTTP server error",
"code": "STATUS_CODE_ERROR"
}
}
]
}
]
}
]
}
+63
View File
@@ -0,0 +1,63 @@
{
"warmup_load": {
"seconds": 5.023,
"workers": 2,
"successful_requests": 1754,
"failed_requests": 0,
"successful_rps": 349.224,
"latency_ms_successes": {
"p50": 3.402,
"p95": 29.977,
"p99": 47.073
}
},
"worker_stopped": {
"firing": true,
"detected_seconds": 27.281,
"depth": 3.0,
"oldest_age_seconds": 25.0,
"worker_busy": 0.0,
"worker_heartbeat_age_seconds": 27.950000047683716,
"resolved": true,
"depth_after": 0.0
},
"postgres_stopped": {
"firing": true,
"detected_seconds": 19.446,
"failed_requests": 1493,
"error_ratio": 0.4429462133684413,
"db_available": 0.0,
"pool_waiting_peak": 1.0,
"trace_id": "0f7c21ea05f16d658179ddb68077e88c",
"resolved": true,
"db_available_after": 1.0
},
"tempo_stopped": {
"workload": {
"seconds": 20.004,
"workers": 2,
"successful_requests": 7177,
"failed_requests": 0,
"successful_rps": 358.785,
"latency_ms_successes": {
"p50": 3.384,
"p95": 30.726,
"p99": 46.204
}
},
"collector_before": {
"memory": "67.89MiB / 256MiB",
"cpu": "0.81%"
},
"collector_during": {
"memory": "73.02MiB / 256MiB",
"cpu": "1.80%"
},
"failed_span_send_records_delta": 842.0,
"max_queue_batches": 32.0,
"queue_limit_batches": 32,
"dropped_spans_from_collector_logs": 906,
"business_api_preserved": true,
"export_resumed": true
}
}
+166
View File
@@ -0,0 +1,166 @@
# Результаты лабораторной7 — оценка4
**23 ноября 2026**, macOS arm64 / Docker Desktop Linux containers. Данные
синтетические. API https://localhost:8443, Grafana https://localhost:13007,
OpenBao operator https://localhost:18200. Все положительные HTTPS-запросы
использовали локальный CA и проверку hostname; insecure flags не применялись.
## Сборка и локальные проверки
```sh
sh scripts/start.sh
export BASE_URL=https://localhost:8443
export CA_FILE="$PWD/secrets/public/ca.crt"
make check
make test
make test-security
GOTOOLCHAIN=go1.26.11 CGO_ENABLED=0 go test ./...
GOTOOLCHAIN=go1.26.11 CGO_ENABLED=0 go vet ./...
```
Публичный HTTPS smoke и отрицательный внешний TLS trust — **PASS**. Go tests
messenger/pipeline/telemetry — PASS, vet exit0. Schema/contract/public tests не
изменялись; обязательная trust matrix заполнена. Python syntax/JSON, shell syntax
и git diff whitespace проверены. Полная необязательная OpenAPI validation не
заявляется как выполненная.
## TLS/mTLS, identities, privileges
```sh
python3 student-tests/verify_tls.py
```
**PASS: 43 TLS/policy checks + 11 runtime hardening checks**.
- API1/API2/broker/Collector: разрешённая identity проходит; no certificate,
foreign CA и wrong DNS SAN при trusted CA отвергнуты.
- API1/API2/dispatcher/worker проверены как отдельные Collector identities.
- Worker не может публиковать job stream; producer/consumer имеют отдельные
usernames/пароли и command/key ACL. Broker proxy привязывает AUTH к SAN.
- Redis sessions/S3/Prometheus/Loki/Tempo используют verified TLS и запрещают
outsider. Все заявленные plaintext loopback ports недоступны из audit namespace.
- Реальный cert login OpenBao worker читает свой path; чужой API path и изменение
policy возвращают403; token TTL ограничен.
- По docker inspect подтверждены read_only, cap_drop ALL, no-new-privileges,
CPU/RAM limits, отсутствие privileged/host network/Docker socket; приложения
non-root и без operator root/unseal mounts.
[Матрица](../contracts/trust-matrix.md), [результат](tls-matrix-grade4.json).
Worker CLI отдельно подтверждает PostgreSQL TLS и запреты чтения password table,
создания bucket, записи staging и broker admin: [least-privilege.json](least-privilege.json).
## Argon2id, ACL, общий rate limit и сессии
```sh
python3 student-tests/verify_security.py
```
**PASS**: новые hashes Argon2id m19456KiB/t2/p1; реальный scrypt hash записан
оператором в synthetic row, успешный HTTPS Basic login обновил его на Argon2id.
Наблюдавшееся время этого HTTPS login с rehash — **116.866ms**.
Один username исчерпал общий для API1/API2 лимит: первый429 на **11-й попытке**,
Retry-After присутствует, обе реплики наблюдались. Посторонний не читает metadata/
content и не загружает в чужой chat; X-User-Id не меняет Bearer identity. После
logout и реального expiry отдельной synthetic Redis session получены401.
Trusted CA с неправильным hostname всё равно отклонён.
Unit benchmark10 hashes на AppleM4/Go1.26.11: **17.680ms/op**,19,927,106B/op,
34allocs/op. Это локальный cost baseline; Docker throttled latency не приравнивается
к нему. Два hash slots/replica и shared budget120 auth/registration requests/minute
ограничивают дорогую работу; глобальный flood способен ограничить легитимный login.
[security-grade4.json](security-grade4.json).
## Ротация, отзыв и sealed/expiry
```sh
python3 student-tests/verify_lifecycle.py
```
**PASS**:
- Worker DB password изменён; прежний пароль отвергнут на новом TLS-соединении.
- Scoped KV обновлён, новый worker pool обработал изображение.
- Worker leaf заменён, старый serial добавлен в denylist, Bao cert binding обновлён.
Старый leaf отвергнут на новом broker connection; новый снова обрабатывает jobs.
- IDs образов до/после совпали: ротация выполнена **без build**.
- После seal Bao API перестал использовать credentials по окончании оставшейся
lease:503 наблюдался через **42.499s**. Это остаток ранее выданного TTL60s,
не обещание фиксированной задержки каждого отказа. Live продолжал отвечать.
- После operator unseal восстановились прежняя сессия и обработка нового upload.
[lifecycle-grade4.json](lifecycle-grade4.json). Работа уже установленных соединений
не называется мгновенно отозванной: тест использует NEW connection, rollover
перезапускает caller для drain. Root/unseal остаются operator-only.
## Сохранность предыдущих лабораторных
```sh
python3 student-tests/verify_variants.py
python3 student-tests/verify_pipeline.py
python3 student-tests/verify_observability.py
python3 student-tests/verify_resilience.py
```
- **Variants PASS:** реальные JPEG/WebP, EXIF/alpha, exact10MiB/40Mpx,413/415,
ACL, checksums и оригинал. Worker peak704,176,128B < limit1,610,612,736B.
- **Pipeline PASS:** actual dispatcher/worker exit86, outbox gap, ready duplicate,
retry/failed registry/audit replay, checksum permanent error. После падения
зафиксированы attempts2 и восстановление lease за **65.362s**.
- **Observability PASS:** incoming W3C → producer → две consumer attempts →
S3/DB/image.process; связанные logs/metrics; private canaries и labels проверены.
- **Resilience PASS:** перезапущены16 core/telemetry/OpenBao сервисов с изменением
StartedAt. Operator hook дождался Bao listener и выполнил unseal. Те же
token/data/original и stored telemetry history сохранились.
| Остановлена реплика | Подтверждённых сообщений | Переходных ошибок | Первый успех surviving API |
|---|---:|---:|---:|
| api1 | 67 | 0 | 0.844s |
| api2 | 65 | 1 | 0.852s |
Переходная ошибка учтена, запрос повторялся с тем же idempotency key; подтверждённые
сообщения найдены в истории, оригинал сохранился. Обе API восстановлены.
Файлы: [variants](variants-grade4.json), [pipeline](pipeline-grade4.json),
[observability](observability-grade4.json), [resilience](resilience.json).
## Чистый запуск
Отдельная исходная копия без .git/.env/secrets/venv; новый CA, новые credentials,
**9 пустых volumes**, project mtusi-lab7-clean-final. Operator init/unseal,
up -d --build --wait, публичный HTTPS smoke и отрицательный TLS trust прошли.
BuildKit cache использовался; это source-copy audit до публикации, а не проверка
скачивания ещё не опубликованной ветки. Порты8444/13008/18201 изолировали стенд.
Временные контейнеры/volumes удалены, основной стенд сохранён.
[clean-start.json](clean-start.json).
## Dependency/image scan
```sh
python3 scripts/scan.py
```
Реальные Trivy0.76.2 image scans финальных API/worker archives и govulncheck1.1.4
на Go1.26.11 выполнены. Scanner не получает Docker socket.
API binary:2 HIGH +2 MEDIUM — transitive Prometheus module. Go trace указывает
model/histogram.init; web/remote-read/config handlers не импортируются приложением.
Worker дополнительно содержит Debian/Python findings, в том числе2 OS CRITICAL
(SQLite/minizip attribution) и1 Python CRITICAL (pip-vendored certifi).
Они сохранены в summary и разобраны по reachable workload; не объявлены исчезнувшими.
Перед final scan обновлены Go TLS/HTTP patches, Python/Pillow, pgx, OTel, crypto/net,
grpc/jwt/compress. [Scan summary](scan-summary.json) и
[triage](../infra/security/scan-triage.md) содержат применимость/остаточные риски.
Zero-CVE и production security completeness не заявляются.
## Повтор инцидентов lab6 на TLS-стенде
`verify_incidents.py` — **PASS**. Worker stop: queue-lag firing27.281s,
после запуска depth0 и resolved. PostgreSQL stop: error-rate firing19.446s,
1493 ответа503, DB availability0; после запуска resolved/availability1.
Tempo stop: бизнес-записи продолжались, export queue≤32 batches; экспорт
восстановился. [incidents-grade4.json](incidents-grade4.json),
[db-incident-trace.json](db-incident-trace.json).
+1
View File
@@ -0,0 +1 @@
{"status":"PASS","postgres_tls":true,"worker_password_table_denied":true,"s3_admin_denied":true,"staging_write_denied":true,"broker_admin_denied":true}
+11
View File
@@ -0,0 +1,11 @@
{
"status": "PASS",
"old_DB_password_new_connection": "rejected",
"new_DB_password": "working",
"leaf_rotation": "worker",
"old_leaf_new_connection": "rejected",
"images_unchanged": true,
"sealed_lease_rejected_seconds": 42.499,
"unsealed_recovery": true,
"original_session_preserved": true
}
+29
View File
@@ -0,0 +1,29 @@
{
"status": "PASS",
"trace_id": "403dab53696c4c959fae377bd070a998",
"request_id": "b097a412-96c8-4495-88bc-584ba4b12f15",
"consumer_attempt_spans": 2,
"events": [
"http.request",
"job.completed",
"job.published",
"job.started"
],
"metrics": {
"http_requests": 1688.0,
"http_histogram": 1688.0,
"jobs_success": 1.0,
"jobs_retry": 1.0,
"ready_histogram": 1.0,
"queue": 0.0,
"pool": 10.0,
"worker_capacity": 1.0,
"memory": 76537856.0
},
"dashboard": {
"title": "MTUSI Messenger — lab7",
"panels": 23
},
"privacy": "PASS",
"low_cardinality": "PASS"
}
+48
View File
@@ -0,0 +1,48 @@
{
"stopped_worker_and_restart": {
"status": "PASS",
"before": {
"api1": "2026-11-23T08:13:47.558920633Z",
"api2": "2026-11-23T08:13:47.55699955Z",
"broker": "2026-11-23T08:13:42.451189756Z"
},
"after": {
"api1": "2026-11-23T08:16:29.329208639Z",
"api2": "2026-11-23T08:16:29.285893097Z",
"broker": "2026-11-23T08:16:29.049437305Z"
}
},
"commit_publish_gap": "PASS: actual dispatcher exit 86 and automatic restart",
"crash_after_objects": {
"status": "PASS",
"recovery_seconds": 65.362,
"attempts": 2
},
"commit_before_ack_and_duplicate": "PASS",
"retry_failed_registry_replay": {
"status": "PASS",
"exhausted_attempts": 2,
"error_code": "retry_exhausted",
"replay_audit_rows": 1,
"ready_replay_rejected": true
},
"permanent_error": "PASS",
"message_replay_after_attachment_failure": "PASS",
"crash_points": [
{
"point": "dispatcher_before_publish",
"armed": false,
"hit_at": "2026-11-23T08:16:35.555382+00:00"
},
{
"point": "worker_after_objects",
"armed": false,
"hit_at": "2026-11-23T08:16:37.002712+00:00"
},
{
"point": "worker_before_ack",
"armed": false,
"hit_at": "2026-11-23T08:17:43.298327+00:00"
}
]
}
+164
View File
@@ -0,0 +1,164 @@
{
"persistence": {
"status": "PASS",
"before": {
"postgres": {
"id": "d98ba586b9a0e24f494d8ed167e68120f7920fdffab8f538b7a3b61748be40ee",
"started_at": "2026-11-23T08:23:48.373077175Z"
},
"redis": {
"id": "e483be3df61477419eb217e5f2970fd4f98a7a8d95a2e80e140bd6a038e0fd00",
"started_at": "2026-11-23T08:23:48.291282425Z"
},
"s3": {
"id": "20f1ad567861244a29a28d6acf23395b635351ac59c51761f757858ceb7feb10",
"started_at": "2026-11-23T08:23:48.286639342Z"
},
"broker": {
"id": "0b0c2bf752dcc3f6fe4cbf4d47587063b842948908d24013658c09579e17f3cd",
"started_at": "2026-11-23T08:23:48.304351092Z"
},
"api1": {
"id": "d462c539ec21bcda5efd801580e36c92de6c8388d07fb5177f82ca35011c9614",
"started_at": "2026-11-23T08:23:48.954853092Z"
},
"api2": {
"id": "3aaa43fa544eb6878759401402fd965d8c67b387af7aad244114bfa5012f7298",
"started_at": "2026-11-23T08:23:49.004133675Z"
},
"dispatcher": {
"id": "20d631fdff308b0db2b807df5382f6cbb42090c2d6840345227e623731483d9c",
"started_at": "2026-11-23T08:23:48.725597009Z"
},
"worker": {
"id": "3a28b118f7c224796ffe14a635cfe7c8f7453f7eb130270b96e3cb51f7052ca1",
"started_at": "2026-11-23T08:23:48.797910467Z"
},
"cleanup": {
"id": "96965c3983811d7fa06154f194037ee84cce72b06b064d38b9b33945956c487d",
"started_at": "2026-11-23T08:23:48.724491467Z"
},
"nginx": {
"id": "ed74d5f9d6e2e1bb77bf57305e7bf7b26fa7acd9fc22f56f38561089462bbf54",
"started_at": "2026-11-23T08:23:49.681158717Z"
},
"otel-collector": {
"id": "05bccf92585e8acf421ebb68baa8a118553a79e8b10f654d8ebb9ed094d5092b",
"started_at": "2026-11-23T08:23:49.393916384Z"
},
"prometheus": {
"id": "68d8706bc55ddcc297867de43b79bb555d9ffdf58523d60b51f691fbaba6d6e3",
"started_at": "2026-11-23T08:23:49.425072092Z"
},
"loki": {
"id": "952b9b75d67dcd4e19a746f6d2767cf0b2327855750f021911bc6431bf7c6efb",
"started_at": "2026-11-23T08:23:49.951155676Z"
},
"tempo": {
"id": "f221d56e8379fa0bfaf6a9284432f773fd466b5b8f0cbca8c0a94081fd601770",
"started_at": "2026-11-23T08:23:49.535264717Z"
},
"grafana": {
"id": "0823ee00162877acb058c8211346866e138fa0d13d72934d6cd43b6f60d7e425",
"started_at": "2026-11-23T08:23:49.646137134Z"
},
"openbao": {
"id": "f83bb95085fd40bcab8b37ced10863d9424c2d9f3409d36944f5a88297cec6af",
"started_at": "2026-11-23T08:23:46.901904383Z"
}
},
"after": {
"postgres": {
"id": "d98ba586b9a0e24f494d8ed167e68120f7920fdffab8f538b7a3b61748be40ee",
"started_at": "2026-11-23T08:24:25.250468595Z"
},
"redis": {
"id": "e483be3df61477419eb217e5f2970fd4f98a7a8d95a2e80e140bd6a038e0fd00",
"started_at": "2026-11-23T08:24:25.254180637Z"
},
"s3": {
"id": "20f1ad567861244a29a28d6acf23395b635351ac59c51761f757858ceb7feb10",
"started_at": "2026-11-23T08:24:25.193353387Z"
},
"broker": {
"id": "0b0c2bf752dcc3f6fe4cbf4d47587063b842948908d24013658c09579e17f3cd",
"started_at": "2026-11-23T08:24:25.212889303Z"
},
"api1": {
"id": "d462c539ec21bcda5efd801580e36c92de6c8388d07fb5177f82ca35011c9614",
"started_at": "2026-11-23T08:24:25.802583054Z"
},
"api2": {
"id": "3aaa43fa544eb6878759401402fd965d8c67b387af7aad244114bfa5012f7298",
"started_at": "2026-11-23T08:24:25.864984345Z"
},
"dispatcher": {
"id": "20d631fdff308b0db2b807df5382f6cbb42090c2d6840345227e623731483d9c",
"started_at": "2026-11-23T08:24:25.584345679Z"
},
"worker": {
"id": "3a28b118f7c224796ffe14a635cfe7c8f7453f7eb130270b96e3cb51f7052ca1",
"started_at": "2026-11-23T08:24:26.603840179Z"
},
"cleanup": {
"id": "96965c3983811d7fa06154f194037ee84cce72b06b064d38b9b33945956c487d",
"started_at": "2026-11-23T08:24:25.663001929Z"
},
"nginx": {
"id": "ed74d5f9d6e2e1bb77bf57305e7bf7b26fa7acd9fc22f56f38561089462bbf54",
"started_at": "2026-11-23T08:24:27.057844596Z"
},
"otel-collector": {
"id": "05bccf92585e8acf421ebb68baa8a118553a79e8b10f654d8ebb9ed094d5092b",
"started_at": "2026-11-23T08:24:26.825416554Z"
},
"prometheus": {
"id": "68d8706bc55ddcc297867de43b79bb555d9ffdf58523d60b51f691fbaba6d6e3",
"started_at": "2026-11-23T08:24:26.863099263Z"
},
"loki": {
"id": "952b9b75d67dcd4e19a746f6d2767cf0b2327855750f021911bc6431bf7c6efb",
"started_at": "2026-11-23T08:24:27.828088346Z"
},
"tempo": {
"id": "f221d56e8379fa0bfaf6a9284432f773fd466b5b8f0cbca8c0a94081fd601770",
"started_at": "2026-11-23T08:24:27.83158068Z"
},
"grafana": {
"id": "0823ee00162877acb058c8211346866e138fa0d13d72934d6cd43b6f60d7e425",
"started_at": "2026-11-23T08:24:27.035950388Z"
},
"openbao": {
"id": "f83bb95085fd40bcab8b37ced10863d9424c2d9f3409d36944f5a88297cec6af",
"started_at": "2026-11-23T08:24:24.310769178Z"
}
}
},
"failover": [
{
"status": "PASS",
"stopped_service": "api1",
"confirmed_messages": 67,
"transient_failures": 0,
"first_survivor_seconds": 0.844,
"original_preserved": true
},
{
"status": "PASS",
"stopped_service": "api2",
"confirmed_messages": 65,
"transient_failures": 1,
"first_survivor_seconds": 0.852,
"original_preserved": true
}
],
"public_failover": {
"status": "PASS",
"output": "python3 tests/resilience.py --mode failover --action-script \"scripts/stop-one.sh\" --base-url \"https://localhost:8443\" --ca-file \"/Users/macbook/Desktop/ВП/mtusi2026lab7/secrets/public/ca.crt\"\nExecuting explicit failover hook; hook output suppressed to avoid leaking secrets.\n{\"observed_instances_before\": 2, \"successful_writes\": 128, \"failed_attempts\": 0, \"first_recovery_seconds\": 0.953}\nPASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence."
},
"metric_history_before_restart": {
"unix_time": 1795422256.863099,
"http_counter_sum": 470.0
},
"telemetry_history_preserved": true
}
+759
View File
@@ -0,0 +1,759 @@
{
"date": "2026-11-23",
"scanner": "aquasec/trivy:0.76.2",
"images": {
"mtusi-lab7-api:local": {
"metadata": {
"Size": 27002880,
"ImageID": "sha256:9a63b804be12402d298b7926f33edaf9757c8737455dab7cdcf474537bfe2279",
"DiffIDs": [
"sha256:0a7bc78be195da9404fe449859c1e317e26bc9083a4bee04dc6b43528388beef"
],
"RepoTags": [
"mtusi-lab7-api:local"
],
"Reference": "mtusi-lab7-api:local",
"ImageConfig": {
"architecture": "arm64",
"created": "2026-11-23T08:26:06.603820628Z",
"history": [
{
"created": "2026-11-23T08:26:06.603820628Z",
"created_by": "COPY /messenger /messenger # buildkit",
"comment": "buildkit.dockerfile.v0"
},
{
"created": "2026-11-23T08:26:06.603820628Z",
"created_by": "USER 65532:65532",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
},
{
"created": "2026-11-23T08:26:06.603820628Z",
"created_by": "ENV APP_HOST=0.0.0.0 APP_PORT=8080",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
},
{
"created": "2026-11-23T08:26:06.603820628Z",
"created_by": "EXPOSE [8080/tcp]",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
},
{
"created": "2026-11-23T08:26:06.603820628Z",
"created_by": "HEALTHCHECK &{[\"CMD\" \"/messenger\" \"healthcheck\"] \"10s\" \"3s\" \"5s\" \"0s\" '\\x03'}",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
},
{
"created": "2026-11-23T08:26:06.603820628Z",
"created_by": "ENTRYPOINT [\"/messenger\"]",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
}
],
"os": "linux",
"rootfs": {
"type": "layers",
"diff_ids": [
"sha256:0a7bc78be195da9404fe449859c1e317e26bc9083a4bee04dc6b43528388beef"
]
},
"config": {
"Healthcheck": {
"Test": [
"CMD",
"/messenger",
"healthcheck"
],
"Interval": 10000000000,
"Timeout": 3000000000,
"StartPeriod": 5000000000,
"Retries": 3
},
"Entrypoint": [
"/messenger"
],
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"APP_HOST=0.0.0.0",
"APP_PORT=8080"
],
"Labels": {
"com.docker.compose.project": "mtusi-lab7",
"com.docker.compose.service": "migrate",
"com.docker.compose.version": "5.0.2"
},
"User": "65532:65532",
"WorkingDir": "/",
"ExposedPorts": {
"8080/tcp": {}
}
}
},
"Layers": [
{
"Size": 27002880,
"Digest": "sha256:9873620f5a820201071403f1e80fb26adfada10a8cd9278a52fd158ee0c8d5bc",
"DiffID": "sha256:0a7bc78be195da9404fe449859c1e317e26bc9083a4bee04dc6b43528388beef"
}
]
},
"results": [
{
"target": "messenger",
"severity_counts": {
"HIGH": 2,
"MEDIUM": 2
},
"findings": [
{
"id": "CVE-2026-42151",
"package": "github.com/prometheus/prometheus",
"installed": "v0.54.1",
"fixed": "0.311.3",
"severity": "HIGH"
},
{
"id": "CVE-2026-42154",
"package": "github.com/prometheus/prometheus",
"installed": "v0.54.1",
"fixed": "0.311.3, 0.305.2",
"severity": "HIGH"
}
]
}
]
},
"mtusi-lab7-worker:local": {
"metadata": {
"Size": 209475584,
"OS": {
"Family": "debian",
"Name": "12.15"
},
"ImageID": "sha256:b75e803b1bb7bf1cf77be126ab70d605b668e1c753266919a5be0d2e43e40469",
"DiffIDs": [
"sha256:3b7c7ecdb9b2a2a7651551c07dc748fee9e27902c8b88c25cb3af3fbbc0a4b87",
"sha256:44899cae61ccc73d5b56156fda33e36c46043b99b08d24eb0211a7c6754aed9f",
"sha256:dbc4fc69750c22190218a7c613525bd6955d0d266e85a68df6a1add26f01f6e0",
"sha256:2ce9d8539c9a479492b1f7c1be89edfa33d33fca8945c37576c05c05c4a431a0",
"sha256:24cea1182a4b29a1bc600bb07332fdda2fa8e0516986cf8410cfe8d95c5d8037",
"sha256:0a7bc78be195da9404fe449859c1e317e26bc9083a4bee04dc6b43528388beef",
"sha256:da52a858bac4411f2974bad9c8d9149b08da0395425592fb9a098a4bb3a966b6"
],
"RepoTags": [
"mtusi-lab7-worker:local"
],
"Reference": "mtusi-lab7-worker:local",
"ImageConfig": {
"architecture": "arm64",
"created": "2026-11-23T08:26:06.671424878Z",
"history": [
{
"created": "2026-10-20T21:32:55Z",
"created_by": "# debian.sh --arch 'arm64' out/ 'bookworm' '@1792531975'",
"comment": "debuerreotype 0.17"
},
{
"created": "2026-10-21T01:04:43.502710555Z",
"created_by": "ENV PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
},
{
"created": "2026-10-21T01:04:43.502710555Z",
"created_by": "RUN /bin/sh -c set -eux; \tapt-get update; \tapt-get install -y --no-install-recommends \t\tca-certificates \t\tnetbase \t\ttzdata \t; \trm -rf /var/lib/apt/lists/* # buildkit",
"comment": "buildkit.dockerfile.v0"
},
{
"created": "2026-10-21T01:04:43.502710555Z",
"created_by": "ENV GPG_KEY=7169605F62C751356D054A26A821E680E5FA6305",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
},
{
"created": "2026-10-21T01:04:43.502710555Z",
"created_by": "ENV PYTHON_VERSION=3.13.16",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
},
{
"created": "2026-10-21T01:04:43.502710555Z",
"created_by": "ENV PYTHON_SHA256=f4b1bfb3c79b5bb11b8d228a12504163b4c0dab4d679828d8f5f26b6cb6ab35d",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
},
{
"created": "2026-10-21T01:18:01.6487303Z",
"created_by": "RUN /bin/sh -c set -eux; \t\tsavedAptMark=\"$(apt-mark showmanual)\"; \tapt-get update; \tapt-get install -y --no-install-recommends \t\tdpkg-dev \t\tg++ \t\tgcc \t\tgnupg \t\tlibbluetooth-dev \t\tlibbz2-dev \t\tlibc6-dev \t\tlibdb-dev \t\tlibffi-dev \t\tlibgdbm-dev \t\tliblzma-dev \t\tlibncursesw5-dev \t\tlibreadline-dev \t\tlibsqlite3-dev \t\tlibssl-dev \t\tmake \t\ttk-dev \t\tuuid-dev \t\twget \t\txz-utils \t\tzlib1g-dev \t; \t\twget -O python.tar.xz \"https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz\"; \techo \"$PYTHON_SHA256 *python.tar.xz\" | sha256sum -c -; \twget -O python.tar.xz.asc \"https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc\"; \tGNUPGHOME=\"$(mktemp -d)\"; export GNUPGHOME; \tgpg --batch --keyserver hkps://keys.openpgp.org --recv-keys \"$GPG_KEY\"; \tgpg --batch --verify python.tar.xz.asc python.tar.xz; \tgpgconf --kill all; \trm -rf \"$GNUPGHOME\" python.tar.xz.asc; \tmkdir -p /usr/src/python; \ttar --extract --directory /usr/src/python --strip-components=1 --file python.tar.xz; \trm python.tar.xz; \t\tcd /usr/src/python; \tgnuArch=\"$(dpkg-architecture --query DEB_BUILD_GNU_TYPE)\"; \t./configure \t\t--build=\"$gnuArch\" \t\t--enable-loadable-sqlite-extensions \t\t--enable-optimizations \t\t--enable-option-checking=fatal \t\t--enable-shared \t\t$(test \"${gnuArch%%-*}\" != 'riscv64' && echo '--with-lto') \t\t--with-ensurepip \t; \tnproc=\"$(nproc)\"; \tEXTRA_CFLAGS=\"$(dpkg-buildflags --get CFLAGS)\"; \tLDFLAGS=\"$(dpkg-buildflags --get LDFLAGS)\"; \tLDFLAGS=\"${LDFLAGS:-} -Wl,--strip-all\"; \tarch=\"$(dpkg --print-architecture)\"; arch=\"${arch##*-}\"; \tcase \"$arch\" in \t\tamd64|arm64) \t\t\tEXTRA_CFLAGS=\"${EXTRA_CFLAGS:-} -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer\"; \t\t\t;; \t\ti386) \t\t\t;; \t\t*) \t\t\tEXTRA_CFLAGS=\"${EXTRA_CFLAGS:-} -fno-omit-frame-pointer\"; \t\t\t;; \tesac; \tmake -j \"$nproc\" \t\t\"EXTRA_CFLAGS=${EXTRA_CFLAGS:-}\" \t\t\"LDFLAGS=${LDFLAGS:-}\" \t; \trm python; \tmake -j \"$nproc\" \t\t\"EXTRA_CFLAGS=${EXTRA_CFLAGS:-}\" \t\t\"LDFLAGS=${LDFLAGS:-} -Wl,-rpath='\\$\\$ORIGIN/../lib'\" \t\tpython \t; \tmake install; \t\tcd /; \trm -rf /usr/src/python; \t\tfind /usr/local -depth \t\t\\( \t\t\t\\( -type d -a \\( -name test -o -name tests -o -name idle_test \\) \\) \t\t\t-o \\( -type f -a \\( -name '*.pyc' -o -name '*.pyo' -o -name 'libpython*.a' \\) \\) \t\t\\) -exec rm -rf '{}' + \t; \t\tldconfig; \t\tapt-mark auto '.*' > /dev/null; \tapt-mark manual $savedAptMark; \tfind /usr/local -type f -executable -not \\( -name '*tkinter*' \\) -exec ldd '{}' ';' \t\t| awk '/=>/ { so = $(NF-1); if (index(so, \"/usr/local/\") == 1) { next }; gsub(\"^/(usr/)?\", \"\", so); printf \"*%s\\n\", so }' \t\t| sort -u \t\t| xargs -rt dpkg-query --search \t\t| awk 'sub(\":$\", \"\", $1) { print $1 }' \t\t| sort -u \t\t| xargs -r apt-mark manual \t; \tapt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \trm -rf /var/lib/apt/lists/*; \t\texport PYTHONDONTWRITEBYTECODE=1; \tpython3 --version; \tpip3 --version # buildkit",
"comment": "buildkit.dockerfile.v0"
},
{
"created": "2026-10-21T01:18:01.781640188Z",
"created_by": "RUN /bin/sh -c set -eux; \tfor src in idle3 pip3 pydoc3 python3 python3-config; do \t\tdst=\"$(echo \"$src\" | tr -d 3)\"; \t\t[ -s \"/usr/local/bin/$src\" ]; \t\t[ ! -e \"/usr/local/bin/$dst\" ]; \t\tln -svT \"$src\" \"/usr/local/bin/$dst\"; \tdone # buildkit",
"comment": "buildkit.dockerfile.v0"
},
{
"created": "2026-10-21T01:18:01.781640188Z",
"created_by": "CMD [\"python3\"]",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
},
{
"created": "2026-11-23T08:08:54.869017595Z",
"created_by": "RUN /bin/sh -c pip install --no-cache-dir Pillow==13.0.0 # buildkit",
"comment": "buildkit.dockerfile.v0"
},
{
"created": "2026-11-23T08:26:06.660022003Z",
"created_by": "COPY /messenger /messenger # buildkit",
"comment": "buildkit.dockerfile.v0"
},
{
"created": "2026-11-23T08:26:06.671424878Z",
"created_by": "COPY worker/process_image.py /opt/process_image.py # buildkit",
"comment": "buildkit.dockerfile.v0"
},
{
"created": "2026-11-23T08:26:06.671424878Z",
"created_by": "USER 65532:65532",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
},
{
"created": "2026-11-23T08:26:06.671424878Z",
"created_by": "ENTRYPOINT [\"/messenger\"]",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
},
{
"created": "2026-11-23T08:26:06.671424878Z",
"created_by": "CMD [\"worker\"]",
"comment": "buildkit.dockerfile.v0",
"empty_layer": true
}
],
"os": "linux",
"rootfs": {
"type": "layers",
"diff_ids": [
"sha256:3b7c7ecdb9b2a2a7651551c07dc748fee9e27902c8b88c25cb3af3fbbc0a4b87",
"sha256:44899cae61ccc73d5b56156fda33e36c46043b99b08d24eb0211a7c6754aed9f",
"sha256:dbc4fc69750c22190218a7c613525bd6955d0d266e85a68df6a1add26f01f6e0",
"sha256:2ce9d8539c9a479492b1f7c1be89edfa33d33fca8945c37576c05c05c4a431a0",
"sha256:24cea1182a4b29a1bc600bb07332fdda2fa8e0516986cf8410cfe8d95c5d8037",
"sha256:0a7bc78be195da9404fe449859c1e317e26bc9083a4bee04dc6b43528388beef",
"sha256:da52a858bac4411f2974bad9c8d9149b08da0395425592fb9a098a4bb3a966b6"
]
},
"config": {
"Cmd": [
"worker"
],
"Entrypoint": [
"/messenger"
],
"Env": [
"PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"GPG_KEY=7169605F62C751356D054A26A821E680E5FA6305",
"PYTHON_VERSION=3.13.16",
"PYTHON_SHA256=f4b1bfb3c79b5bb11b8d228a12504163b4c0dab4d679828d8f5f26b6cb6ab35d"
],
"Labels": {
"com.docker.compose.project": "mtusi-lab7",
"com.docker.compose.service": "worker",
"com.docker.compose.version": "5.0.2"
},
"User": "65532:65532",
"ArgsEscaped": true
}
},
"Layers": [
{
"Size": 100270080,
"Digest": "sha256:41b2195c355367079ebad200f9591fe3c2cb886c3b1e67abaaf2090dc11c04d9",
"DiffID": "sha256:3b7c7ecdb9b2a2a7651551c07dc748fee9e27902c8b88c25cb3af3fbbc0a4b87"
},
{
"Size": 8833024,
"Digest": "sha256:074ae8d79fff1d55806696e8c8523f4673142e457282438b20a41822320e9c34",
"DiffID": "sha256:44899cae61ccc73d5b56156fda33e36c46043b99b08d24eb0211a7c6754aed9f"
},
{
"Size": 41406464,
"Digest": "sha256:a38430ada044646b68410fd10c67cb3f8eeba0ea0f4a78375927caf977ad3ee8",
"DiffID": "sha256:dbc4fc69750c22190218a7c613525bd6955d0d266e85a68df6a1add26f01f6e0"
},
{
"Size": 5120,
"Digest": "sha256:c2342846f501062931ed08e64a6cafaa477613d54b83cbac3e81954d9297b806",
"DiffID": "sha256:2ce9d8539c9a479492b1f7c1be89edfa33d33fca8945c37576c05c05c4a431a0"
},
{
"Size": 31953408,
"Digest": "sha256:62ce0f198501765402ff8caa31ec1f8b882893aee639503fc6bcff67ef90587c",
"DiffID": "sha256:24cea1182a4b29a1bc600bb07332fdda2fa8e0516986cf8410cfe8d95c5d8037"
},
{
"Size": 27002880,
"Digest": "sha256:9873620f5a820201071403f1e80fb26adfada10a8cd9278a52fd158ee0c8d5bc",
"DiffID": "sha256:0a7bc78be195da9404fe449859c1e317e26bc9083a4bee04dc6b43528388beef"
},
{
"Size": 4608,
"Digest": "sha256:82a42f8e0cfc4f147d0c8a23f49cdc1990ff59310378b8722c6b329c1e4d235c",
"DiffID": "sha256:da52a858bac4411f2974bad9c8d9149b08da0395425592fb9a098a4bb3a966b6"
}
]
},
"results": [
{
"target": "/scan/worker.tar (debian 12.15)",
"severity_counts": {
"HIGH": 47,
"LOW": 102,
"MEDIUM": 126,
"UNKNOWN": 19,
"CRITICAL": 2
},
"findings": [
{
"id": "CVE-2026-109518",
"package": "apt",
"installed": "2.6.1",
"fixed": "2.6.2",
"severity": "HIGH"
},
{
"id": "CVE-2026-53613",
"package": "bsdutils",
"installed": "1:2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53615",
"package": "bsdutils",
"installed": "1:2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-78410",
"package": "bsdutils",
"installed": "1:2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-41992",
"package": "gzip",
"installed": "1.12-1",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-54369",
"package": "libacl1",
"installed": "2.3.1-3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-109518",
"package": "libapt-pkg6.0",
"installed": "2.6.1",
"fixed": "2.6.2",
"severity": "HIGH"
},
{
"id": "CVE-2026-53613",
"package": "libblkid1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53615",
"package": "libblkid1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-78410",
"package": "libblkid1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53613",
"package": "libmount1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53615",
"package": "libmount1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-78410",
"package": "libmount1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2025-69720",
"package": "libncursesw6",
"installed": "6.4-4",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2025-6020",
"package": "libpam-modules",
"installed": "1.5.2-6+deb12u2",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2025-6020",
"package": "libpam-modules-bin",
"installed": "1.5.2-6+deb12u2",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2025-6020",
"package": "libpam-runtime",
"installed": "1.5.2-6+deb12u2",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2025-6020",
"package": "libpam0g",
"installed": "1.5.2-6+deb12u2",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53613",
"package": "libsmartcols1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53615",
"package": "libsmartcols1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-78410",
"package": "libsmartcols1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2025-7458",
"package": "libsqlite3-0",
"installed": "3.40.1-2+deb12u2",
"fixed": null,
"severity": "CRITICAL"
},
{
"id": "CVE-2026-11822",
"package": "libsqlite3-0",
"installed": "3.40.1-2+deb12u2",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-11824",
"package": "libsqlite3-0",
"installed": "3.40.1-2+deb12u2",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-119373",
"package": "libsqlite3-0",
"installed": "3.40.1-2+deb12u2",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-119374",
"package": "libsqlite3-0",
"installed": "3.40.1-2+deb12u2",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-119379",
"package": "libsqlite3-0",
"installed": "3.40.1-2+deb12u2",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-84782",
"package": "libssl3",
"installed": "3.0.22-1~deb12u1",
"fixed": "3.0.22-1~deb12u2",
"severity": "HIGH"
},
{
"id": "CVE-2026-16742",
"package": "libsystemd0",
"installed": "252.39-1~deb12u2",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2025-69720",
"package": "libtinfo6",
"installed": "6.4-4",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-16742",
"package": "libudev1",
"installed": "252.39-1~deb12u2",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53613",
"package": "libuuid1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53615",
"package": "libuuid1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-78410",
"package": "libuuid1",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53613",
"package": "mount",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53615",
"package": "mount",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-78410",
"package": "mount",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2025-69720",
"package": "ncurses-base",
"installed": "6.4-4",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2025-69720",
"package": "ncurses-bin",
"installed": "6.4-4",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-84782",
"package": "openssl",
"installed": "3.0.22-1~deb12u1",
"fixed": "3.0.22-1~deb12u2",
"severity": "HIGH"
},
{
"id": "CVE-2026-9538",
"package": "perl-base",
"installed": "5.36.0-7+deb12u4",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53613",
"package": "util-linux",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53615",
"package": "util-linux",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-78410",
"package": "util-linux",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53613",
"package": "util-linux-extra",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-53615",
"package": "util-linux-extra",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2026-78410",
"package": "util-linux-extra",
"installed": "2.38.1-5+deb12u3",
"fixed": null,
"severity": "HIGH"
},
{
"id": "CVE-2023-45853",
"package": "zlib1g",
"installed": "1:1.2.13.dfsg-1",
"fixed": null,
"severity": "CRITICAL"
},
{
"id": "CVE-2026-85091",
"package": "zlib1g",
"installed": "1:1.2.13.dfsg-1",
"fixed": null,
"severity": "HIGH"
}
]
},
{
"target": "Python",
"severity_counts": {
"CRITICAL": 1,
"HIGH": 5,
"MEDIUM": 2,
"LOW": 1
},
"findings": [
{
"id": "GHSA-6q48-6c7w-9gw2",
"package": "certifi",
"installed": "2026.6.17",
"fixed": "2026.10.18",
"severity": "CRITICAL"
},
{
"id": "CVE-2026-114613",
"package": "msgpack",
"installed": "1.1.2",
"fixed": "1.2.3",
"severity": "HIGH"
},
{
"id": "GHSA-6v7p-g79w-8964",
"package": "msgpack",
"installed": "1.1.2",
"fixed": "1.2.1",
"severity": "HIGH"
},
{
"id": "CVE-2025-47273",
"package": "setuptools",
"installed": "70.3.0",
"fixed": "78.1.1",
"severity": "HIGH"
},
{
"id": "CVE-2026-97687",
"package": "urllib3",
"installed": "2.7.0",
"fixed": "2.8.0",
"severity": "HIGH"
},
{
"id": "CVE-2026-97689",
"package": "urllib3",
"installed": "2.7.0",
"fixed": "2.8.0",
"severity": "HIGH"
}
]
},
{
"target": "messenger",
"severity_counts": {
"HIGH": 2,
"MEDIUM": 2
},
"findings": [
{
"id": "CVE-2026-42151",
"package": "github.com/prometheus/prometheus",
"installed": "v0.54.1",
"fixed": "0.311.3",
"severity": "HIGH"
},
{
"id": "CVE-2026-42154",
"package": "github.com/prometheus/prometheus",
"installed": "v0.54.1",
"fixed": "0.311.3, 0.305.2",
"severity": "HIGH"
}
]
}
]
}
},
"go": {
"tool": "govulncheck v1.1.4",
"toolchain": "go1.26.11",
"ids": [
"GO-2026-5264",
"GO-2026-5381",
"GO-2026-5662",
"GO-2026-5710"
],
"function_locations": [
"github.com/prometheus/prometheus/model/histogram.init"
]
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"status": "PASS",
"argon2id": "m=19456KiB,t=2,p=1",
"legacy_rehash_ms": 116.866,
"outsider_metadata_content_upload": "denied",
"spoofed_header": "ignored",
"logout": "401",
"session_expiry": "401",
"shared_rate_limit_first_429_attempt": 11,
"api_instances": [
"api-1",
"api-2"
],
"hostname_mismatch": "rejected"
}
+61
View File
@@ -0,0 +1,61 @@
{
"status": "PASS",
"checks": {
"api1_authorized_identity": "PASS",
"api1_no_certificate_denied": "PASS",
"api1_foreign_CA_denied": "PASS",
"api1_trusted_wrong_SAN_denied": "PASS",
"api2_authorized_identity": "PASS",
"api2_no_certificate_denied": "PASS",
"api2_foreign_CA_denied": "PASS",
"api2_trusted_wrong_SAN_denied": "PASS",
"broker_authorized_identity": "PASS",
"broker_no_certificate_denied": "PASS",
"broker_foreign_CA_denied": "PASS",
"broker_trusted_wrong_SAN_denied": "PASS",
"otel-collector_authorized_identity": "PASS",
"otel-collector_no_certificate_denied": "PASS",
"otel-collector_foreign_CA_denied": "PASS",
"otel-collector_trusted_wrong_SAN_denied": "PASS",
"api1_collector_mTLS": "PASS",
"api2_collector_mTLS": "PASS",
"dispatcher_collector_mTLS": "PASS",
"dispatcher_broker_mTLS": "PASS",
"worker_cannot_publish_job_stream": "PASS",
"redis_verified_TLS": "PASS",
"redis_outsider_denied": "PASS",
"s3_verified_TLS": "PASS",
"s3_outsider_denied": "PASS",
"prometheus_verified_TLS": "PASS",
"prometheus_outsider_denied": "PASS",
"loki_verified_TLS": "PASS",
"loki_outsider_denied": "PASS",
"tempo_verified_TLS": "PASS",
"tempo_outsider_denied": "PASS",
"broker_plaintext_bypass_closed": "PASS",
"redis_plaintext_bypass_closed": "PASS",
"s3_plaintext_bypass_closed": "PASS",
"otel-collector_plaintext_bypass_closed": "PASS",
"prometheus_plaintext_bypass_closed": "PASS",
"loki_plaintext_bypass_closed": "PASS",
"tempo_plaintext_bypass_closed": "PASS",
"bao_cert_login": "PASS",
"bao_secret_worker_policy": "PASS",
"bao_secret_api1_policy": "PASS",
"bao_sys_policies_acl_injected_policy": "PASS",
"bao_bounded_token_TTL": "PASS"
},
"runtime_hardening": {
"api1": "PASS",
"api2": "PASS",
"worker": "PASS",
"dispatcher": "PASS",
"cleanup": "PASS",
"otel-collector": "PASS",
"prometheus": "PASS",
"loki": "PASS",
"tempo": "PASS",
"grafana": "PASS",
"nginx": "PASS"
}
}
File diff suppressed because it is too large Load Diff
+125
View File
@@ -0,0 +1,125 @@
{
"orientation": {
"status": "PASS",
"variants": {
"thumbnail": {
"content_type": "image/jpeg",
"height": 256,
"name": "thumbnail",
"sha256": "335b4953e981a975642374e12196a4701e353972f223c1a7e850ac5998588f1a",
"size_bytes": 1270,
"width": 160
},
"crop": {
"content_type": "image/jpeg",
"height": 128,
"name": "crop",
"sha256": "b7f4884df301163117ebb3189f6141a9e376cc6d94804e2f56ce38e0dc3dd047",
"size_bytes": 886,
"width": 128
},
"optimized": {
"content_type": "image/webp",
"height": 320,
"name": "optimized",
"sha256": "577722d04127a774de08f674717fa03e3058124395f9ee31a949e6f508e86b43",
"size_bytes": 210,
"width": 200
}
}
},
"alpha": {
"status": "PASS",
"variants": {
"thumbnail": {
"content_type": "image/jpeg",
"height": 4,
"name": "thumbnail",
"sha256": "a89b0af8a3c520ca079ed01f7a6579b39fdf0a593d5ff94b7a5128c194f3d065",
"size_bytes": 631,
"width": 8
},
"crop": {
"content_type": "image/jpeg",
"height": 128,
"name": "crop",
"sha256": "257edb1205654cf43e411c9fc333ee5544c2dc8753470ab667cdafbfeae4ff7c",
"size_bytes": 883,
"width": 128
},
"optimized": {
"content_type": "image/webp",
"height": 4,
"name": "optimized",
"sha256": "f4e61263caab4e749c64fc56091797191901d5affdb15ee2d828d905c429e950",
"size_bytes": 44,
"width": 8
}
}
},
"large": {
"status": "PASS",
"variants": {
"thumbnail": {
"content_type": "image/jpeg",
"height": 128,
"name": "thumbnail",
"sha256": "126971107bc487792a7b813c01e037c58140ab0a039d4c7fd0cdbd26a9d9d781",
"size_bytes": 1142,
"width": 256
},
"crop": {
"content_type": "image/jpeg",
"height": 128,
"name": "crop",
"sha256": "4e67b8bf92db7d696303a433822a79479ca6d8ac5ca6bf2c87e5f4514ed3fa4a",
"size_bytes": 886,
"width": 128
},
"optimized": {
"content_type": "image/webp",
"height": 640,
"name": "optimized",
"sha256": "8e5a8340d7a7b9c37e935e090bb34494e588b7534a6d091aba33aca5ba83a267",
"size_bytes": 1540,
"width": 1280
}
}
},
"boundary": {
"status": "PASS",
"variants": {
"thumbnail": {
"content_type": "image/jpeg",
"height": 160,
"name": "thumbnail",
"sha256": "d8d8358f529fd170984ee7926c54e9f6ead7d6a397fd6b803a6c20af197a2ce2",
"size_bytes": 1270,
"width": 256
},
"crop": {
"content_type": "image/jpeg",
"height": 128,
"name": "crop",
"sha256": "4e67b8bf92db7d696303a433822a79479ca6d8ac5ca6bf2c87e5f4514ed3fa4a",
"size_bytes": 886,
"width": 128
},
"optimized": {
"content_type": "image/webp",
"height": 800,
"name": "optimized",
"sha256": "a9bc2a93f44b92bf58d3c1a2f53390b21f0330b073411886eeccac3b12eb6769",
"size_bytes": 1904,
"width": 1280
}
}
},
"byte_limits_corrupt_pixel_limits": "PASS",
"private_bucket_limited_credentials": "PASS",
"worker_memory_bytes": {
"memory.current": 16441344,
"memory.max": 1610612736,
"memory.peak": 704176128
}
}
+74
View File
@@ -0,0 +1,74 @@
module mtusi-messenger
go 1.26.0
require (
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.13.0
github.com/minio/madmin-go/v3 v3.0.95
github.com/minio/minio-go/v7 v7.0.95
github.com/redis/go-redis/v9 v9.14.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/log v1.47.0
go.opentelemetry.io/otel/metric v1.47.0
go.opentelemetry.io/otel/sdk v1.47.0
go.opentelemetry.io/otel/sdk/log v1.47.0
go.opentelemetry.io/otel/sdk/metric v1.47.0
go.opentelemetry.io/otel/trace v1.47.0
golang.org/x/crypto v0.59.0
)
require (
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/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/go-ole/go-ole v1.3.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.3 // indirect
github.com/klauspost/compress v1.20.5 // indirect
github.com/klauspost/cpuid/v2 v2.2.11 // indirect
github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/minio/crc64nvme v1.0.2 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.59.1 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/prometheus/prom2json v1.4.0 // indirect
github.com/prometheus/prometheus v0.54.1 // indirect
github.com/rs/xid v1.6.0 // indirect
github.com/safchain/ethtool v0.4.1 // indirect
github.com/secure-io/sio-go v0.3.1 // indirect
github.com/shirou/gopsutil/v3 v3.24.5 // indirect
github.com/shoenig/go-m1cpu v0.1.6 // indirect
github.com/tinylib/msgp v1.3.0 // indirect
github.com/tklauser/go-sysconf v0.3.14 // indirect
github.com/tklauser/numcpus v0.8.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
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.85.0 // indirect
google.golang.org/protobuf v1.36.12 // indirect
)
+176
View File
@@ -0,0 +1,176 @@
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.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/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
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-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
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.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
github.com/klauspost/compress v1.20.5/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/lufia/plan9stats v0.0.0-20240909124753-873cd0166683 h1:7UMa6KCCMjZEMDtTVdcGu0B1GmmC7QJKiCCjyTAWQy0=
github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683/go.mod h1:ilwx/Dta8jXAgpFYFvSWEMwxmbWXyiUHkd5FwyKhb5k=
github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=
github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
github.com/minio/crc64nvme v1.0.2 h1:6uO1UxGAD+kwqWWp7mBFsi5gAse66C4NXO8cmcVculg=
github.com/minio/crc64nvme v1.0.2/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
github.com/minio/madmin-go/v3 v3.0.95 h1:KRy4NIpTLKrHcuTQbKrwKs3SvGoe+ZAHT2Pbl1zJxDc=
github.com/minio/madmin-go/v3 v3.0.95/go.mod h1:pMLdj9OtN0CANNs5tdm6opvOlDFfj0WhbztboZAjRWE=
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/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
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/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
github.com/prometheus/common v0.59.1 h1:LXb1quJHWm1P6wq/U824uxYi4Sg0oGvNeUm1z5dJoX0=
github.com/prometheus/common v0.59.1/go.mod h1:GpWM7dewqmVYcd7SmRaiWVe9SSqjf0UrwnYnpEZNuT0=
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
github.com/prometheus/prom2json v1.4.0 h1:2AEOsd1ebqql/p9u0IWgCpUAteAAf9Lnf/SVyieqer4=
github.com/prometheus/prom2json v1.4.0/go.mod h1:DmcIMPspQD/fMyFCYti5qJJbuEnqDh3DGoooO0sgr4w=
github.com/prometheus/prometheus v0.54.1 h1:vKuwQNjnYN2/mDoWfHXDhAsz/68q/dQDb+YbcEqU7MQ=
github.com/prometheus/prometheus v0.54.1/go.mod h1:xlLByHhk2g3ycakQGrMaU8K7OySZx98BzeCR99991NY=
github.com/redis/go-redis/v9 v9.14.0 h1:u4tNCjXOyzfgeLN+vAZaW1xUooqWDqVEsZN0U01jfAE=
github.com/redis/go-redis/v9 v9.14.0/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/safchain/ethtool v0.4.1 h1:S6mEleTADqgynileXoiapt/nKnatyR6bmIHoF+h2ADo=
github.com/safchain/ethtool v0.4.1/go.mod h1:XLLnZmy4OCRTkksP/UiMjij96YmIsBfmBQcs7H6tA48=
github.com/secure-io/sio-go v0.3.1 h1:dNvY9awjabXTYGsTF1PiCySl9Ltofk9GA3VdWlo7rRc=
github.com/secure-io/sio-go v0.3.1/go.mod h1:+xbkjDzPjwh4Axd07pRKSNriS9SCiYksWnZqdnfpQxs=
github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI=
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU=
github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k=
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=
github.com/tklauser/go-sysconf v0.3.14 h1:g5vzr9iPFFz24v2KZXs/pvpvh8/V9Fw6vQK5ZZb78yU=
github.com/tklauser/go-sysconf v0.3.14/go.mod h1:1ym4lWMLUOhuBOPGtRcJm7tEGX4SCYNEEEtghGG/8uY=
github.com/tklauser/numcpus v0.8.0 h1:Mx4Wwe/FjZLeQsK/6kt2EOepwwSl7SmJrK5bV/dXYgY=
github.com/tklauser/numcpus v0.8.0/go.mod h1:ZJZlAY+dmR4eut8epnzf0u/VwodKmryxR8txiloSqBE=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 h1:5WVp40k2fJHuc5BtNTgKk+EugKFT8Eg3lywFfCPI/nE=
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0/go.mod h1:59nH0RYCGHRlwt15WyioeSYINBbuObeBpTowPhEKWHY=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0 h1:7kszRN4Ze5GeAkUnBjBSUIunVBMA+mZIG04auueqguM=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.47.0/go.mod h1:CLzakYy8jOdkBfcveCWYkeKJxujcF4xPhh2Z7IfE98U=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
go.opentelemetry.io/otel/metric/x v0.69.0 h1:DjRLr15H83v+hCW7JA9NoJvOkYTtmq5YoDRbe9deYpM=
go.opentelemetry.io/otel/metric/x v0.69.0/go.mod h1:uVvsMPMFFyj/HUQfrUnH3JjnOQ1dwFDorgFLRBasM0k=
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
go.opentelemetry.io/otel/sdk/log v1.47.0 h1:W4N/ZfgpkRRnmARnqYoQ6BrWA0mrj8IzVDNLlpmUJZY=
go.opentelemetry.io/otel/sdk/log v1.47.0/go.mod h1:Wu74Z2EmOKXi2FleSNAb0Hyau2G+r5kubSEMJw5aAMs=
go.opentelemetry.io/otel/sdk/log/logtest v0.23.0 h1:j3pm42QCrKYYLLkI6OrV1QHFkUfDA6/4EP+Y1PzggLg=
go.opentelemetry.io/otel/sdk/log/logtest v0.23.0/go.mod h1:zt0gEnuTZgDvqvczHwYswz93eqMaIr6upTTsdV/HUlU=
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
go.uber.org/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.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
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.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
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.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
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.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
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=
+16
View File
@@ -0,0 +1,16 @@
# Build MinIO from a pinned commit of the official upstream source.
FROM golang:1.26.11-alpine3.23@sha256:23f198931d4bd83b4f5a613bd75656257ae8bf832dcbc2db80e1050b5219ca2a AS build
ADD --checksum=sha256:be6d0bd3696c3a13a35f02d3a0280b64319c67918b4501c5c3d87f96d000085c https://codeload.github.com/minio/minio/tar.gz/refs/tags/RELEASE.2025-10-15T17-29-55Z /source.tar.gz
WORKDIR /src
RUN tar -xzf /source.tar.gz --strip-components=1 -C /src
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOMAXPROCS=2 go build -p 2 -trimpath -buildvcs=false \
-ldflags='-s -w -X github.com/minio/minio/cmd.Version=2025-10-15T17:29:55Z -X github.com/minio/minio/cmd.ReleaseTag=RELEASE.2025-10-15T17-29-55Z -X github.com/minio/minio/cmd.CommitID=9e49d5e7a648f00e26f2246f4dc28e6b07f8c84a -X github.com/minio/minio/cmd.CopyrightYear=2025' \
-o /minio .
FROM busybox:1.37.0-musl
COPY --from=build /minio /minio
COPY --from=build /src/LICENSE /licenses/MinIO-LICENSE
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
RUN mkdir -p /data
ENTRYPOINT ["/minio"]
+8
View File
@@ -0,0 +1,8 @@
FROM application AS app_binary
FROM python:3.13.16-slim-bookworm@sha256:73aa5faee130c60da030e105ec971ccf57473fbd22ce73bd6fc9ba99a40b838d
RUN pip install --no-cache-dir Pillow==13.0.0
COPY --from=app_binary /messenger /messenger
COPY worker/process_image.py /opt/process_image.py
USER 65532:65532
ENTRYPOINT ["/messenger"]
CMD ["worker"]
+43
View File
@@ -0,0 +1,43 @@
#!/bin/sh
set -eu
upstream=/run/nginx-upstream.conf
write_servers() {
if [ "$1" = 1 ]; then
printf '%s\n' 'server api1:8080 resolve max_fails=0;'
fi
if [ "$2" = 1 ]; then
printf '%s\n' 'server api2:8080 resolve max_fails=0;'
fi
}
# With no healthy replica, keep both reachable so API can return its normal
# 401/503 JSON responses instead of Nginx reporting "no live upstreams".
write_servers 1 1 > "$upstream"
monitor() {
sleep 2
while :; do
ready1=0
ready2=0
curl -fsS --max-time 2 --cacert /run/ca/ca.crt --cert /run/tls/cert.crt --key /run/tls/key.key -o /dev/null https://api1:8080/health/ready && ready1=1 || true
curl -fsS --max-time 2 --cacert /run/ca/ca.crt --cert /run/tls/cert.crt --key /run/tls/key.key -o /dev/null https://api2:8080/health/ready && ready2=1 || true
if [ "$ready1" = 0 ] && [ "$ready2" = 0 ]; then
ready1=1
ready2=1
fi
next=$(mktemp /run/nginx-upstream.XXXXXX)
write_servers "$ready1" "$ready2" > "$next"
if cmp -s "$next" "$upstream"; then
rm -f "$next"
else
mv "$next" "$upstream"
nginx -t >/dev/null 2>&1 && nginx -s reload
fi
sleep 1
done
}
monitor &
exec nginx -g 'daemon off;'
+46
View File
@@ -0,0 +1,46 @@
pid /run/nginx.pid;
events {}
http {
access_log /dev/stdout;
error_log /dev/stderr notice;
resolver 127.0.0.11 valid=2s ipv6=off;
upstream messenger_api {
zone messenger_api 64k;
include /run/nginx-upstream.conf;
keepalive 16;
}
server {
listen 8443 ssl;
ssl_certificate /run/tls/cert.crt;
ssl_certificate_key /run/tls/key.key;
ssl_protocols TLSv1.2 TLSv1.3;
add_header Strict-Transport-Security "max-age=86400" always;
client_max_body_size 0;
client_body_timeout 20s;
location / {
proxy_request_buffering off;
proxy_buffering off;
proxy_pass https://messenger_api;
proxy_ssl_verify on;
proxy_ssl_trusted_certificate /run/ca/ca.crt;
proxy_ssl_server_name on;
proxy_ssl_name messenger-api;
proxy_ssl_certificate /run/tls/cert.crt;
proxy_ssl_certificate_key /run/tls/key.key;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 500ms;
proxy_send_timeout 65s;
proxy_read_timeout 65s;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
}
}
+7 -6
View File
@@ -1,7 +1,8 @@
# Конфигурация наблюдаемости — реализовать # Observability retained from lab6
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend. Collector/Prometheus/Loki/Tempo/Grafana provisioning and dashboard remain in this
directory. Lab7 changes transport: TLS sidecars isolate native loopback listeners;
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`. application OTLP, exporter, scrape and datasource connections verify CA/hostname
and service identities. See `contracts/trust-matrix.md` and `infra/security/`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён. Grafana is HTTPS localhost13007, password is local secret. No insecure TLS flags.
Signals and alert/runbook semantics remain documented in signals.md/runbook.md.
+23
View File
@@ -0,0 +1,23 @@
groups:
- name: messenger-slo
rules:
- record: messenger:api_error_ratio:rate1m
expr: (sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*",status_class="5xx"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*"}[1m])), 0.001)
- record: messenger:api_availability:rate5m
expr: 1 - (sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*",status_class="5xx"}[5m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*"}[5m])), 0.001)
- alert: MessengerHighErrorRate
expr: messenger:api_error_ratio:rate1m > 0.05
for: 10s
labels:
severity: warning
annotations:
summary: Business API 5xx ratio exceeds 5% over 1 minute
description: Inspect database spans, DB availability and pool panels; see infra/otel/runbook.md.
- alert: MessengerQueueLag
expr: max(messenger_queue_oldest_age_seconds) > 10 and max(messenger_queue_depth) > 0
for: 10s
labels:
severity: warning
annotations:
summary: Oldest queued job exceeds 10 seconds
description: Compare worker busy/capacity, job outcomes and queue age; see infra/otel/runbook.md.
+82
View File
@@ -0,0 +1,82 @@
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:14318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 128
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 64
send_batch_max_size: 128
exporters:
prometheus:
endpoint: 127.0.0.1:18889
resource_to_telemetry_conversion:
enabled: true
otlphttp/tempo:
endpoint: https://tempo:4318
timeout: 2s
tls:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/cert.crt
key_file: /run/tls/key.key
sending_queue:
enabled: true
num_consumers: 2
queue_size: 32
block_on_overflow: false
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 2s
max_elapsed_time: 5s
otlphttp/loki:
endpoint: https://loki:3100/otlp
timeout: 2s
tls:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/cert.crt
key_file: /run/tls/key.key
sending_queue:
enabled: true
num_consumers: 2
queue_size: 32
block_on_overflow: false
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 2s
max_elapsed_time: 5s
extensions:
health_check:
endpoint: 127.0.0.1:13133
service:
extensions: [health_check]
telemetry:
logs:
encoding: json
metrics:
level: detailed
readers:
- pull:
exporter:
prometheus:
host: 127.0.0.1
port: 18888
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
@@ -0,0 +1,669 @@
{
"uid": "mtusi-messenger",
"title": "MTUSI Messenger — lab7",
"schemaVersion": 39,
"version": 1,
"refresh": "5s",
"tags": [
"mtusi",
"lab7"
],
"time": {
"from": "now-15m",
"to": "now"
},
"panels": [
{
"id": 1,
"title": "API RPS (business routes)",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_instance_id) (rate(messenger_http_requests_total{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m]))",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
}
},
{
"id": 2,
"title": "Business API error ratio: 5xx / all",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger:api_error_ratio:rate1m",
"legendFormat": "5xx ratio"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 3,
"title": "API p50 from histogram",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m])))",
"legendFormat": "p50"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 4,
"title": "API p95 from histogram",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m])))",
"legendFormat": "p95"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 5,
"title": "API p99 from histogram",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 6,
"title": "Worker job outcomes",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(messenger_jobs_processed_total[1m]))",
"legendFormat": "{{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
}
},
{
"id": 7,
"title": "Worker p95 processing duration",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[5m])))",
"legendFormat": "p95"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 8,
"title": "End-to-end p95 time to ready",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p95"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 9,
"title": "Queue depth",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_queue_depth)",
"legendFormat": "queued"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 10,
"title": "Oldest queued job age",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_queue_oldest_age_seconds)",
"legendFormat": "oldest"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 11,
"title": "DB pool used / waiting",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_db_pool_used",
"legendFormat": "used {{service_instance_id}}"
},
{
"refId": "B",
"expr": "messenger_db_pool_waiting",
"legendFormat": "waiting {{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 12,
"title": "DB pool wait rate",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_instance_id) (rate(messenger_db_pool_acquire_wait_total[1m]))",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
}
},
{
"id": 13,
"title": "Worker saturation: busy / capacity",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_worker_busy / messenger_worker_capacity",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 14,
"title": "Worker capacity",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_worker_capacity",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 15,
"title": "Container CPU time rate (includes decoder)",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 56,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "rate(messenger_container_cpu_seconds_total[1m])",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "cores"
},
"overrides": []
}
},
{
"id": 16,
"title": "Container memory",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 56,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_container_memory_bytes",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
}
},
{
"id": 17,
"title": "Database available",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 64,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_db_available",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 18,
"title": "SLI availability, rolling 5m (SLO 99%)",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 64,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger:api_availability:rate5m",
"legendFormat": "availability"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 19,
"title": "Local alert states",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 72,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "ALERTS{alertname=~\"Messenger.*\"}",
"legendFormat": "{{alertname}} {{alertstate}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 20,
"title": "Collector queued export batches",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 72,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "otelcol_exporter_queue_size",
"legendFormat": "{{exporter}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 21,
"title": "Collector failed trace exports",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 80,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "otelcol_exporter_send_failed_spans_total",
"legendFormat": "{{exporter}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 22,
"title": "SDK exporter errors",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 80,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_telemetry_export_errors",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 23,
"title": "Worker heartbeat age (stale if stopped)",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 88,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "time() - messenger_process_last_observed_seconds{service_name=\"messenger-worker\"}",
"legendFormat": "worker heartbeat age"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
}
],
"annotations": {
"list": []
}
}
@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: Messenger
orgId: 1
folder: MTUSI
type: file
disableDeletion: false
editable: false
updateIntervalSeconds: 10
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,55 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
isDefault: true
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
secureJsonData:
tlsCACert: $TLS_CA_PEM
tlsClientCert: $TLS_CERT_PEM
tlsClientKey: $TLS_KEY_PEM
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
editable: false
jsonData:
derivedFields:
- name: TraceID
matcherRegex: '"trace_id":"([a-f0-9]{32})"'
datasourceUid: tempo
url: $${__value.raw}
tlsAuth: true
tlsAuthWithCACert: true
secureJsonData:
tlsCACert: $TLS_CA_PEM
tlsClientCert: $TLS_CERT_PEM
tlsClientKey: $TLS_KEY_PEM
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: -1m
spanEndTimeShift: 1m
filterByTraceID: true
filterBySpanID: false
serviceMap:
datasourceUid: prometheus
tlsAuth: true
tlsAuthWithCACert: true
secureJsonData:
tlsCACert: $TLS_CA_PEM
tlsClientCert: $TLS_CERT_PEM
tlsClientKey: $TLS_KEY_PEM
+32
View File
@@ -0,0 +1,32 @@
auth_enabled: false
server:
http_listen_address: 127.0.0.1
http_listen_port: 13100
grpc_listen_address: 127.0.0.1
common:
instance_addr: 127.0.0.1
path_prefix: /loki
replication_factor: 1
ring:
kvstore:
store: inmemory
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
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
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
+24
View File
@@ -0,0 +1,24 @@
global:
scrape_interval: 3s
evaluation_interval: 5s
rule_files:
- /etc/prometheus/alerts.yaml
scrape_configs:
- job_name: messenger
static_configs:
- targets:
- otel-collector:8889
scheme: https
tls_config:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/cert.crt
key_file: /run/tls/key.key
- job_name: collector
static_configs:
- targets:
- otel-collector:8888
scheme: https
tls_config:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/cert.crt
key_file: /run/tls/key.key
+42
View File
@@ -0,0 +1,42 @@
# Локальная диагностика
Открыть Grafana → MTUSI → **MTUSI Messenger — lab7**. В Explore доступны Prometheus, Loki и Tempo. Пароль admin хранится локально в `secrets/grafana_admin_password`, в Git его нет.
## MessengerQueueLag
Условие: oldest queued job > 10 s при depth > 0 в течение 10 s. Интервал оценки — 5 s, scrape — 3 s.
1. Посмотреть Queue depth и Oldest queued job age: растут ли они вместе.
2. Посмотреть Worker heartbeat age и busy/capacity. Старый heartbeat при busy=0 означает отсутствие свежих наблюдений worker, а не доказательство его здоровья.
3. Найти `job.published` в Loki и trace upload в Tempo. Если producer есть, а нового consumer нет, искать недоступный worker/доставку. Если consumer есть с error, посмотреть его S3/DB child spans.
4. После устранения причины наблюдать jobs outcome=success, снижение depth/age, свежий heartbeat и resolved (alert исчезает из активных).
Для демонстрации: `docker compose --env-file .env stop worker`, загрузить изображение; восстановить `docker compose --env-file .env start worker`. Проверки автоматизированы в `student-tests/verify_incidents.py`.
## MessengerHighErrorRate
Условие: 5xx / все бизнес-запросы > 5% за 1 минуту в течение 10 s. Health исключены. Ошибки клиента 400/401/404 не входят в числитель.
1. Посмотреть Business API error ratio и API percentiles.
2. По `X-Trace-Id` ответа открыть trace в Tempo. В Loki фильтровать `trace_id` или `request_id`.
3. Для отказа PostgreSQL видны error spans `db.pool.acquire`/`db.select`, `messenger_db_available=0` и ожидание пула. Длительность HTTP без DB error сама по себе не доказывает отказ БД.
4. Восстановить PostgreSQL. Проверить успешные запросы, DB availability=1 и падение error ratio в движущемся окне. Resolved может наступить после обновления окна и нескольких scrape/evaluation.
## Tempo недоступен
1. API продолжает записи; проверить бизнес-операцию, а не только `/health/live`.
2. В Prometheus посмотреть `otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"}` и `otelcol_exporter_queue_size`.
3. Collector queue ограничена 32 batch requests, retry — 5 s; SDK queue — 256 spans/log records, exporter timeout — 2 s. Ожидание backend не переносится в HTTP handler.
4. При переполнении/исчерпании retry данные telemetry могут быть потеряны. В JSON-логах Collector финальная потеря содержит `dropped_items`. Счётчик failed sends не следует считать числом уникальных потерянных трасс.
5. После восстановления проверить свежий trace. Старые потерянные spans автоматически не восстанавливаются из бизнес-БД.
## SLI/SLO
SLI: доля бизнес HTTP-запросов без 5xx за скользящие **5 минут**. SLO: **≥99%**.
```promql
1 - (sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*",status_class="5xx"}[5m])) or vector(0))
/ clamp_min(sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*"}[5m])), 0.001)
```
SLO оценивается на окне с реальным трафиком; при отсутствии запросов правило не должно порождать ошибку деления. Alert использует более короткое 1m окно и порог 5% для локальной диагностики. Это не burn-rate исследование оценки 5.
+53
View File
@@ -0,0 +1,53 @@
# Схема сигналов v1
SDK: OpenTelemetry Go traces/metrics **1.47.0**, logs API/SDK **1.47.0**, log exporter **0.23.0**. Resource schema URL — OTel semantic conventions **1.37.0**; прикладные имена и labels ниже зафиксированы собственной схемой `mtusi-messenger/telemetry-v1`.
Resources: `service.name` = messenger-api / messenger-worker / messenger-dispatcher; `service.version=lab6-v1` (версия перенесённой business instrumentation; deployment lab7 использует TLS), `service.instance.id` = api-1/api-2/worker-1/dispatcher-1, `deployment.environment.name=lab`. Collector превращает resource attrs в Prometheus labels, например service_name.
| Prometheus metric | Тип, единица | Labels |
|---|---|---|
| messenger_http_requests_total | counter, requests | method, route template, status_class |
| messenger_http_duration_seconds_bucket/count/sum | histogram, seconds | те же |
| messenger_jobs_processed_total | counter, attempts | job_type, outcome |
| messenger_job_duration_seconds_bucket/count/sum | histogram, seconds | job_type, outcome |
| messenger_time_to_ready_seconds_bucket/count/sum | histogram, seconds | job_type |
| messenger_queue_depth | gauge, jobs | queue; только dispatcher |
| messenger_queue_oldest_age_seconds | gauge, seconds | queue; только dispatcher |
| messenger_db_pool_used/idle/waiting/capacity | gauge, connections/acquires | resource instance |
| messenger_db_pool_acquire_wait_total | counter, empty pool acquires | resource instance |
| messenger_db_pool_acquire_wait_duration_seconds_total | counter, cumulative seconds | resource instance |
| messenger_worker_busy/capacity | gauge, attempts/slots | worker instance |
| messenger_process_cpu_seconds_total | counter, Go process CPU seconds | instance |
| messenger_container_cpu_seconds_total | counter, cgroup CPU seconds including decoder | instance |
| messenger_process_memory_bytes | gauge, Go runtime reserved memory (Sys), не RSS | instance |
| messenger_container_memory_bytes/limit_bytes | gauge, cgroup bytes | instance |
| messenger_process_last_observed_seconds | gauge, Unix timestamp | instance |
| messenger_db_available | gauge, 0/1 | dispatcher |
| messenger_telemetry_export_errors | gauge, cumulative SDK export errors | instance |
`waiting` — незавершённые Acquire; EmptyAcquire counter показывает обращения к пустому пулу. Busy/capacity — текущая занятость обработчиков, а не CPU%. E2E время измерено от created_at job в транзакции durable acceptance до COMMIT ready, включает queue wait и retry. Replay использует исходное время принятия.
Percentiles вычисляются объединением histogram buckets реплик:
```promql
histogram_quantile(0.95,
sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name="messenger-api",route!~"/health/.*"}[1m])))
```
p50 и p99 используют 0.50 и 0.99. Единицы всех duration panels — секунды. Суммируются buckets, не percentiles отдельных реплик. Полные исполняемые запросы находятся в `grafana/dashboards/messenger.json`.
## Логи и трассы
API log event `http.request`: timestamp, severity, service.name, method, route template, status, duration_ms, request_id, trace_id, span_id. Worker — `job.started`, `job.completed`; dispatcher — `job.published`.
Технические request_id/job_id допустимы только в логах/трассах для корреляции синтетических работ. В labels метрик они отсутствуют. SQL text/args, URL/query, filename, headers Authorization, пароли, токены, текст сообщения и содержимое файлов не записываются.
HTTP server span принимает W3C traceparent/tracestate. Upload транзакционно сохраняет их в job. Producer span публикует свой контекст в разрешённых полях JSON брокера; consumer span извлекает его как parent. Повторы образуют новые producer/consumer ветки того же trace. S3, Redis sessions, DB acquire/query/commit и image.process имеют реальные дочерние spans.
Log body — структурный JSON, дополнительно отправляемый OTLP Log SDK с trace/span context. В Grafana Loki TraceID derived field открывает Tempo; поиск по trace_id показывает связанные события. Заголовок X-Trace-Id добавлен для диагностики; X-Request-Id и бизнес-контракт сохранены.
## Буферизация
SDK: batch queue 256, batch 64, export interval 500 ms, exporter timeout 2 s, retry SDK выключен; metrics interval 2 s. Collector: memory limiter 128 MiB со spike 32 MiB, hard limit контейнера 256 MiB; batch size 64/max128; по 32 batches и 2 consumers для traces/logs, неблокирующее переполнение, retry deadline 5 s. Метрики предоставляются ограниченным набором series на pull endpoint Collector; Prometheus хранит историю в volume. Retention storage — 24 h.
При отказе telemetry допускаются потери signals. Ошибки SDK учитываются отдельно; Collector показывает failed exports/queue, а финальные drops записывает с dropped_items. Business transaction от успешности экспорта не зависит.
+24
View File
@@ -0,0 +1,24 @@
server:
http_listen_address: 127.0.0.1
http_listen_port: 13200
grpc_listen_address: 127.0.0.1
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:14318
grpc:
endpoint: 127.0.0.1:14317
ingester:
max_block_duration: 1m
compactor:
compaction:
block_retention: 24h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
+2
View File
@@ -0,0 +1,2 @@
FROM nginx:1.29.1-alpine3.22
RUN apk add --no-cache curl
+4
View File
@@ -0,0 +1,4 @@
FROM python:3.13.16-slim-bookworm@sha256:73aa5faee130c60da030e105ec971ccf57473fbd22ce73bd6fc9ba99a40b838d
COPY infra/security/tls_proxy.py /tls_proxy.py
USER 65532:65532
ENTRYPOINT ["python3","/tls_proxy.py"]
+65
View File
@@ -0,0 +1,65 @@
# Security boundary
TLS roots are generated by the operator in `secrets/operator/ca.key` (never mounted
in services). Each service receives only its leaf directory plus the public CA.
Leaf lifetime: 7 days. Root lifetime: 365 days. Keys are generated, never in Git
or images. `scripts/pki.py` is idempotent; it does not silently replace a CA.
The native backend processes Redis/MinIO/Collector/Prometheus/Loki/Tempo share
only their corresponding TLS-sidecar network namespace (`network_mode:
service:tls-...`). They bind plaintext listeners to 127.0.0.1 on distinct ports.
Only the sidecar binds the network-facing port. No plaintext port is published.
The proxy verifies client CA, expiry, DNS SAN allowlist and serial denylist on
EVERY new connection. It disables tickets and reloads leaf files per connection.
For broker it additionally parses bounded RESP frames, binds AUTH/HELLO username
to the certificate SAN, and restricts consumer XADD to the invalid-envelope DLQ;
Redis independently enforces producer/consumer command/key ACLs.
A connection can stay alive until its finite 75s socket timeout; certificate
rotation restarts the affected caller to drain its old connections. Denylist
checks refer to NEW connections. No claim of revoking already completed actions.
PostgreSQL uses native TLS and verify-full URLs; separate API/worker/dispatcher/
cleanup database roles. Only the operator migration identity owns schema. API
must read password hashes to authenticate; worker cannot read users. S3 policies
separate API staging writes from worker originals/variants writes. MinIO admin
credentials exist only at the server and one-shot operator bootstrap.
OpenBao uses native TLS, non-dev persistent file storage, cert auth bound to exact
leaf certificates and a read-only policy for each KV path. Tokens: TTL60s/max120s.
Services reauthenticate every20s; this is renewal by scoped reauthentication,
not use of a permanent bootstrap token. Revocation replaces exact cert bindings.
If refresh fails, the last granted lease remains valid only until its deadline;
API then returns contract 503 (liveness stays up), workers exit75 and restart
fail-closed until authority recovery. Secrets are loaded only from Bao; no file
or plaintext fallback. Secret rotation restarts only the affected process/pool,
without building an image. Bootstrap and renewal remain explicit operator tasks.
## Operator commands
```sh
sh scripts/start.sh
python3 scripts/bao-operator.py seal
python3 scripts/bao-operator.py unseal
python3 scripts/rotate-db-secret.py
python3 scripts/rotate-leaf.py worker
```
The operator owns `secrets/operator/bao-init.json`, root token and unseal share;
file mode0600 under mode0700 directory. Neither OpenBao nor apps mount this
operator directory. One-share Shamir is a local teaching compromise; production
requires separated custodians / protected auto-unseal. Restart hook explicitly
runs as operator and unseals using LOCAL operator material; it is not server-side
unattended unseal. Keep an offline protected backup; losing it can make Bao data
unrecoverable. Never delete volumes to recover a forgotten unseal key.
App/worker are non-root; read-only root filesystems, no-new-privileges and
cap_drop ALL apply to runtime services. Writable volumes contain state, bounded
tmpfs contains temporary processing data. One-shot volume ownership init uses
only CHOWN, no network; this is the documented exception, not application power.
Docker socket/host network/privileged mode are absent. Operator audit is a profile,
not a production service, and explicitly mounts audit leaf material read-only.
Runtime secret bind files have mode0444 inside mounts so non-root Linux UIDs can read them. The enclosing host secrets directory stays0700; operator CA key/root token/unseal file stay0600 and are never runtime mounts. Each container receives only its own named files/leaf directory.
Redis sessions: отдельный user api ограничен session:*/login:* и GET/SET/DEL/INCR/EXPIRE/EVAL; CONFIG/FLUSHALL/чужие prefixes не разрешены. Operator health/expiry использует отдельную identity.
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
export PGPASSWORD="$(cat /run/secrets/postgres_password)"
exec psql -X -v ON_ERROR_STOP=1 -h postgres -U messenger -d messenger -f /bootstrap/db-grants.sql
+10
View File
@@ -0,0 +1,10 @@
ui = false
storage "file" { path = "/bao/data" }
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/ca/ca.crt"
tls_min_version = "tls12"
}
api_addr = "https://openbao:8200"
+3
View File
@@ -0,0 +1,3 @@
local all all trust
hostssl all all 0.0.0.0/0 scram-sha-256
hostssl all all ::/0 scram-sha-256
+3
View File
@@ -0,0 +1,3 @@
path "secret/api1" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/api2" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/cleanup" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/dispatcher" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/migrate" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/worker" {
capabilities = ["read"]
}
+39
View File
@@ -0,0 +1,39 @@
# Разбор результатов сканирования зависимостей и образов — 23 ноября 2026
Повторный запуск: `python3 scripts/scan.py` после сборки образов. Trivy 0.76.2
проверяет сохранённые Docker-архивы, без доступа к Docker socket. Govulncheck 1.1.4
использует Go 1.26.11 — ту же версию, что и сборка приложения.
Сводка находится в `evidence/scan-summary.json`.
Проверены исполняемый файл приложения, ОС, Python и зависимости образа worker.
Это не проверка каждого инфраструктурного образа и не доказательство полного
отсутствия уязвимостей.
Перед итоговым сканированием обновлены:
- Go 1.26.8 → 1.26.11: исправления X509/TLS/HTTP;
- Python 3.13.7 → 3.13.16, Pillow 12 → 13;
- pgx 5.7.6 → 5.13.0, OpenTelemetry 1.38 → 1.47;
- x/crypto 0.42 → 0.59, x/net 0.43 → 0.63;
- grpc 1.75 → 1.85, jwt 4.5.0 → 4.5.2, compress 1.18 → 1.20.5.
Точные версии и digest закреплены в Dockerfile и зависимостях Go. После обновлений
выполнены регрессионные проверки бизнес-функций и TLS.
| Группа находок | Применимость и принятое решение |
|---|---|
| Уязвимости Go HTTP/TLS/X509, pgx и обработки изображений Pillow в перенесённой версии | Актуальны: эти компоненты обрабатывают сетевые запросы и недоверенные изображения. Установлены исправленные версии, образы пересобраны, тесты повторены. Внутренняя сеть сама по себе не считается исправлением. |
| GO-2026-5264/5381/5662/5710, модуль Prometheus через madmin | Приложение импортирует только `github.com/prometheus/prometheus/model/histogram`; это проверяется командой `go list -deps ./cmd/messenger`. Оно не подключает обработчики remote-read, config и веб-интерфейса Prometheus, не использует Azure OAuth remote-write. Указанный сканером `histogram.init` не доказывает достижимость уязвимых веб-обработчиков. Косвенная зависимость сохранена до совместимого обновления madmin. Этот вывод относится к исполняемому файлу приложения, а не к отдельному контейнеру Prometheus. |
| CVE-2023-45853, zlib/minizip | Описание относится к функции записи ZIP в minizip, а не к используемой распаковке PNG через zlib. Worker декодирует PNG/JPEG и кодирует JPEG/WebP; ZIP не создаётся, minizip не вызывается. Находка пакета Debian сохранена в результатах. |
| CVE-2025-7458, SQLite | Конвейер worker не открывает SQLite и не выполняет SQLite-запросы. Приложение использует PostgreSQL, обработка Pillow принимает PNG/JPEG. Пакет остаётся в базовом образе Python, но в проверяемом сценарии входные данные в SQLite не передаются. |
| certifi внутри pip, GHSA-6q48-6c7w-9gw2 | Во время работы приложение не использует requests/certifi для доверия внешним адресам: клиенты Go и Python явно доверяют локальному CA. Подпроцесс обработки не получает URL. Pip устанавливает закреплённый Pillow при сборке. Обновления базового образа и pip всё равно необходимы; находка не объявляется безопасной для любого использования. |
| Другие находки Debian: mount/PAM/systemd/apt и библиотеки | Применимость зависит от конкретного пути выполнения. Запрещены mount capabilities, повышение привилегий и установка пакетов во время работы; используются non-root, read-only rootfs и ограниченный подпроцесс. Находки высокой важности остаются в сводке. Для промышленного выпуска нужны дальнейшее сокращение/обновление образа и разбор отдельных уведомлений. Учебная изоляция не устраняет сами CVE. |
## Ограничения анализа
Базы сканеров обновляются, поэтому количество находок — снимок на дату проверки,
а не оценка безопасности в баллах. Изоляция уменьшает последствия, но не исправляет
достижимую ошибку нативного декодера.
Оставшиеся находки явно сохранены и объяснены с учётом выполняемых операций.
Полное отсутствие CVE и завершённая промышленная защита не заявляются.
+29
View File
@@ -0,0 +1,29 @@
# Модель угроз — лабораторная 7, оценка 4
**Защищаемые активы:** хеши паролей, Bearer-сессии, права доступа к чатам,
оригиналы/варианты/staging, целостность заданий, сервисные credentials, ключи PKI,
сохранённая телеметрия и состояние OpenBao.
**Участники:** анонимный клиент, авторизованный пользователь вне чата, клиент
с другим сертификатом доверенного CA, неисправный сервис, скомпрометированный
worker в пределах выданной роли и локальный оператор.
Компрометация хоста, root или самого оператора не покрывается этим учебным стендом.
| Конкретная угроза | Механизм защиты | Воспроизводимая отрицательная проверка |
|---|---|---|
| Перехват соединения (MITM) или подмена сервера | TLS с проверкой CA и hostname, без отключения верификации | `make test-security`; неверный hostname в `verify_security` |
| Обход балансировщика и прямой доступ к API | Порты реплик не опубликованы; mTLS и проверка SAN балансировщика; собственный сертификат API разрешён только для health | `verify_tls`: обе реплики отклоняют запросы без сертификата, с чужим CA и посторонним SAN |
| Клиент доверенного CA выдаёт себя за отправителя заданий | Список разрешённых SAN, разделение портов, привязка Redis AUTH и команд к identity, Redis ACL | `verify_tls`: worker не может выполнить XADD в поток заданий; посторонний клиент не допускается к broker |
| Посторонний сервис отправляет поддельную телеметрию | mTLS Collector с разрешёнными SAN, отдельные identities для сбора метрик | `verify_tls`: посторонний клиент не допускается к приёму данных; прямой локальный listener недоступен извне |
| Чтение чужих вложений или подмена пользовательского заголовка | Bearer-сессия, проверка участия в чате в БД, отсутствие публичных объектов S3 | `verify_security`: чужие metadata/content/upload недоступны, X-User-Id не меняет пользователя |
| Исчерпание CPU/RAM массовыми попытками входа | Argon2id 19 MiB/t2/p1; два параллельных хеширования на реплику; общий Redis-лимит 120 запросов/мин и 10 попыток/мин на username | `verify_security`: общий 429/Retry-After; измерение стоимости Argon2id |
| Worker читает секреты API или хеши паролей | Привязка OpenBao к точному сертификату и scoped policy, отдельная роль БД, ограниченные S3-prefixes | `verify_tls`: разрешения/запреты OpenBao; команда worker `security-audit` |
| Утечка или дальнейшее использование старой сервисной identity | Ограниченный срок сертификата/token, запрет старого serial, замена cert-auth binding, перезапуск пула соединений | `verify_lifecycle`: старые пароль и сертификат отклоняются на новых соединениях |
| Sealed OpenBao приводит к бессрочному использованию старых credentials | Срок lease; после истечения API возвращает 503, worker завершается; сетевые таймауты ограничены | `verify_lifecycle`: seal → истечение lease и 503 → восстановление после unseal |
| Вредоносное изображение исчерпывает ресурсы | Лимиты 10 MiB/40 млн пикселей, подпроцесс 1 GiB с таймаутом, worker CPU1/RAM1536 MiB/tmpfs128 MiB | `verify_variants` и проверки восстановления pipeline |
| Секреты попадают в логи или трассы | Безопасные поля событий, отсутствие SQL-аргументов/заголовков/тела запроса, шаблоны маршрутов в labels | `verify_observability`: поиск специально заданных секретных значений и проверка labels |
Не заявляется защита от злонамеренного оператора хоста, полной потери компьютера
или неограниченная доступность при массовой атаке на login. Общий лимит входа
осознанно ограничивает доступность авторизации ради ограничения дорогой работы.
+83
View File
@@ -0,0 +1,83 @@
"""Bounded mTLS TCP proxy. The backend shares this network namespace and
binds only loopback. Certificate chain AND DNS SAN role are mandatory.
Each new connection reloads leaf and denylist: no session resumption cache.
"""
import os, socket, ssl, threading, time, json
from pathlib import Path
ROLE=os.environ['PROXY_ROLE']
ALLOWED=set(os.environ['ALLOWED_IDENTITIES'].split(','))
PORTS=[tuple(map(int,p.split(':'))) for p in os.environ['PORT_MAP'].split(',')]
PER_PORT=json.loads(os.environ.get("PORT_IDENTITIES","{}"))
SLOTS=threading.BoundedSemaphore(64)
def serve(conn,upstream,port):
try:
conn.settimeout(5)
ctx=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);ctx.minimum_version=ssl.TLSVersion.TLSv1_2
ctx.load_cert_chain('/run/tls/cert.crt','/run/tls/key.key');ctx.load_verify_locations('/run/ca/ca.crt');ctx.verify_mode=ssl.CERT_REQUIRED
ctx.options |= ssl.OP_NO_TICKET
with ctx.wrap_socket(conn,server_side=True) as client:
cert=client.getpeercert();names={v for k,v in cert.get('subjectAltName',[]) if k=='DNS'}
revoked=Path('/run/ca/revoked-serials').read_text().lower().split()
if not names.intersection(set(PER_PORT.get(str(port),list(ALLOWED)))) or cert.get('serialNumber','').lower().lstrip('0') in [s.lstrip('0') for s in revoked]:return
principal=next(iter(names.intersection(set(PER_PORT.get(str(port),list(ALLOWED))))))
with socket.create_connection(('127.0.0.1',upstream),timeout=3) as backend:
client.settimeout(75);backend.settimeout(75)
# Two blocking directions; finite socket timeouts, bounded connections.
def copy(a,b):
try:
while True:
data=a.recv(32768)
if not data:break
b.sendall(data)
except (OSError,ssl.SSLError):pass
finally:
try:b.shutdown(socket.SHUT_WR)
except OSError:pass
def redis_commands():
try:
stream=client.makefile('rb')
while True:
header=stream.readline(128)
if not header:break
if not header.startswith(b'*'):break
count=int(header[1:]);args=[];wire=bytearray(header)
if not 1<=count<=64:break
for _ in range(count):
size=stream.readline(128)
if not size.startswith(b'$'):raise ValueError('invalid RESP')
n=int(size[1:])
if not 0<=n<=1048576:raise ValueError('oversized command')
value=stream.read(n+2)
if len(value)!=n+2:raise ValueError('truncated RESP')
args.append(value[:-2]);wire.extend(size);wire.extend(value)
op=args[0].lower()
allowed={b'ping',b'hello',b'auth',b'client'}
if principal=='worker':allowed|={b'xgroup',b'xautoclaim',b'xreadgroup',b'xack',b'xdel',b'xadd'}
if principal=='dispatcher':allowed|={b'xadd'}
if principal!='operator':
if op not in allowed:break
if op==b'auth' and (len(args)!=3 or args[1].decode()!=principal):break
if op==b'hello' and b'auth' in [a.lower() for a in args]:
i=[a.lower() for a in args].index(b'auth')
if args[i+1].decode()!=principal:break
if op==b'xadd':
expected=b'attachment.invalid.dlq' if principal=='worker' else b'attachment.jobs.v1'
if len(args)<2 or args[1]!=expected:break
backend.sendall(wire)
except (OSError,ValueError,IndexError,UnicodeError):pass
finally:
try:backend.shutdown(socket.SHUT_WR)
except OSError:pass
t=threading.Thread(target=redis_commands if ROLE=='broker' else copy,args=() if ROLE=='broker' else (client,backend),daemon=True)
t.start();copy(backend,client);t.join(timeout=1)
except (OSError,ssl.SSLError):conn.close()
finally:SLOTS.release()
def listen(port,upstream):
with socket.socket() as s:
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1);s.bind(('0.0.0.0',port));s.listen(32)
while True:
conn,_=s.accept()
if not SLOTS.acquire(blocking=False):conn.close();continue
threading.Thread(target=serve,args=(conn,upstream,port),daemon=True).start()
for port,upstream in PORTS:threading.Thread(target=listen,args=(port,upstream),daemon=True).start()
while True:time.sleep(3600)
+64
View File
@@ -0,0 +1,64 @@
package database
import (
"context"
"embed"
"fmt"
"io/fs"
"sort"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
//go:embed migrations/*.sql
var migrations embed.FS
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
return err
}
defer tx.Rollback(ctx)
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(202602)`); err != nil {
return err
}
if _, err = tx.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())`); err != nil {
return err
}
entries, err := fs.ReadDir(migrations, "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 {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
part := strings.SplitN(entry.Name(), "_", 2)[0]
version, parseErr := strconv.Atoi(part)
if parseErr != nil {
return fmt.Errorf("invalid migration name %s", entry.Name())
}
var applied bool
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=$1)`, version).Scan(&applied); err != nil {
return err
}
if applied {
continue
}
sqlBytes, readErr := migrations.ReadFile("migrations/" + entry.Name())
if readErr != nil {
return readErr
}
if _, err = tx.Exec(ctx, string(sqlBytes)); err != nil {
return fmt.Errorf("migration %s: %w", entry.Name(), err)
}
if _, err = tx.Exec(ctx, `INSERT INTO schema_migrations(version) VALUES($1)`, version); err != nil {
return err
}
}
return tx.Commit(ctx)
}
@@ -0,0 +1,31 @@
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(btrim(display_name)) > 0 AND char_length(display_name) <= 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(btrim(title)) > 0 AND char_length(title) <= 100),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text text NOT NULL CHECK (char_length(btrim(text)) > 0 AND char_length(text) <= 4000),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
@@ -0,0 +1,13 @@
CREATE TABLE message_idempotency (
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
method text NOT NULL,
path text NOT NULL,
idempotency_key text NOT NULL,
request_hash bytea NOT NULL,
message_id uuid REFERENCES messages(id) ON DELETE CASCADE,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (user_id, method, path, idempotency_key)
);
CREATE INDEX message_idempotency_created_at_idx
ON message_idempotency (created_at);
@@ -0,0 +1,30 @@
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
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}$'),
status text NOT NULL DEFAULT 'ready' CHECK (status='ready'),
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX attachments_chat_idx ON attachments(chat_id,created_at,id);
-- Durable intent is committed BEFORE any S3 PUT. A crashed upload remains
-- visible to the cleanup process even if its ready metadata never committed.
CREATE TABLE attachment_uploads (
id uuid PRIMARY KEY,
object_key text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX attachment_uploads_created_idx ON attachment_uploads(created_at);
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE messages ADD CONSTRAINT messages_text_check CHECK (char_length(text)<=4000);
ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}';
ALTER TABLE messages ADD CONSTRAINT messages_body_check
CHECK (char_length(btrim(text))>0 OR cardinality(attachment_ids)>0);
ALTER TABLE messages ADD CONSTRAINT messages_attachments_limit CHECK (cardinality(attachment_ids)<=10);
@@ -0,0 +1,37 @@
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
ALTER TABLE attachments ALTER COLUMN status SET DEFAULT 'queued';
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check 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 '[]';
CREATE TABLE attachment_jobs (
id uuid PRIMARY KEY,
attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id) ON DELETE CASCADE,
pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version=1),
staging_key text NOT NULL UNIQUE,
state text NOT NULL DEFAULT 'queued' CHECK (state IN ('queued','processing','ready','failed')),
attempts integer NOT NULL DEFAULT 0,
max_attempts integer NOT NULL DEFAULT 5 CHECK (max_attempts BETWEEN 1 AND 20),
next_at timestamptz NOT NULL DEFAULT clock_timestamp(),
lease_until timestamptz,
lease_token uuid,
error_code text,
staging_deleted_at timestamptz,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX attachment_jobs_due_idx ON attachment_jobs(state,next_at);
-- Same transaction as attachment + job; repeated publication is intentional.
CREATE TABLE attachment_outbox (
job_id uuid PRIMARY KEY REFERENCES attachment_jobs(id) ON DELETE CASCADE,
published_at timestamptz,
publications integer NOT NULL DEFAULT 0
);
CREATE TABLE attachment_replays (
id bigserial PRIMARY KEY,
job_id uuid NOT NULL REFERENCES attachment_jobs(id),
previous_error text NOT NULL,
replayed_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
-- Internal CLI-only, one-shot crash injection. No HTTP endpoint exposes it.
CREATE TABLE pipeline_faults (point text PRIMARY KEY, armed boolean NOT NULL DEFAULT true, hit_at timestamptz);
@@ -0,0 +1,4 @@
-- Persist causal context in the same transaction as durable acceptance/outbox.
ALTER TABLE attachment_jobs ADD COLUMN traceparent text NOT NULL DEFAULT '';
ALTER TABLE attachment_jobs ADD COLUMN tracestate text NOT NULL DEFAULT '';
ALTER TABLE attachment_jobs ADD COLUMN request_id text NOT NULL DEFAULT '';
+263
View File
@@ -0,0 +1,263 @@
package messenger
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/jackc/pgx/v5"
"mtusi-messenger/internal/telemetry"
)
const MaxUploadBytes int64 = 10 * 1024 * 1024
const MaxImagePixels int64 = 40000000
type Attachment struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
func tooLarge() *apiError {
return &apiError{status: 413, code: "payload_too_large", message: "Превышен лимит изображения"}
}
func invalidImage() *apiError {
return &apiError{status: 415, code: "unsupported_media_type", message: "Требуется корректный PNG или JPEG"}
}
func rollbackUpload(tx pgx.Tx) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
_ = tx.Rollback(ctx)
}
func validFilename(s string) bool {
if !utf8.ValidString(s) || strings.TrimSpace(s) == "" || utf8.RuneCountInString(s) > 255 {
return false
}
for _, c := range s {
if c == '/' || c == '\\' || unicode.IsControl(c) {
return false
}
}
return true
}
func (a *API) isMember(r *http.Request, uid, chatID string) *apiError {
ctx, cancel := a.dbContext(r.Context())
defer cancel()
var member bool
if err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`, chatID, uid).Scan(&member); err != nil {
return unavailable()
}
if !member {
return missing()
}
return nil
}
func (a *API) uploadAttachment(r *http.Request, uid, chatID string) (response, *apiError) {
if e := a.isMember(r, uid, chatID); e != nil {
return response{}, e
}
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil || len(query) != 1 || len(query["filename"]) != 1 || !validFilename(query.Get("filename")) {
return response{}, bad("Неверное имя файла")
}
kind, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || (kind != "image/png" && kind != "image/jpeg") {
return response{}, invalidImage()
}
if r.ContentLength > MaxUploadBytes {
return response{}, tooLarge()
}
ctx, cancel := context.WithTimeout(r.Context(), 45*time.Second)
defer cancel()
// One decoder/temporary original per replica bounds RAM and tmpfs usage.
select {
case a.uploadSlots <- struct{}{}:
defer func() { <-a.uploadSlots }()
case <-ctx.Done():
return response{}, unavailable()
}
file, err := os.CreateTemp("", "upload-*")
if err != nil {
return response{}, unavailable()
}
defer os.Remove(file.Name())
defer file.Close()
hash := sha256.New()
size, err := io.CopyBuffer(io.MultiWriter(file, hash), io.LimitReader(r.Body, MaxUploadBytes+1), make([]byte, 32*1024))
if size > MaxUploadBytes {
return response{}, tooLarge()
}
if err != nil {
return response{}, bad("Загрузка прервана")
}
if size == 0 {
return response{}, invalidImage()
}
file.Seek(0, io.SeekStart)
config, format, err := image.DecodeConfig(file)
if err != nil || (format != "png" && format != "jpeg") || "image/"+format != kind {
return response{}, invalidImage()
}
if config.Width < 1 || config.Height < 1 || int64(config.Width) > MaxImagePixels/int64(config.Height) {
return response{}, tooLarge()
}
file.Seek(0, io.SeekStart)
// Decode after the dimension guard to reject corrupt payloads, not just
// apparently valid headers. The decoded bitmap is never persisted.
if e := validateImage(file); e != nil {
return response{}, e
}
file.Seek(0, io.SeekStart)
id := newID()
key := "staging/" + id
dbctx, dbcancel := a.dbContext(ctx)
_, err = a.db.Exec(dbctx, `INSERT INTO attachment_uploads(id,object_key) VALUES($1,$2)`, id, key)
dbcancel()
if err != nil {
return response{}, unavailable()
}
tx, err := a.db.Begin(ctx)
if err != nil {
return response{}, unavailable()
}
defer rollbackUpload(tx)
// Cleanup and upload use the same lock. Cleanup cannot delete an object
// while its upload/metadata transaction is in progress.
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,4))`, key); err != nil {
return response{}, unavailable()
}
var pending bool
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachment_uploads WHERE id=$1)`, id).Scan(&pending); err != nil || !pending {
return response{}, unavailable()
}
putctx, putcancel := context.WithTimeout(ctx, 20*time.Second)
err = a.objects.Put(putctx, key, file, size, kind)
putcancel()
if err != nil {
return response{}, unavailable()
}
att := Attachment{ID: id, ChatID: chatID, OwnerID: uid, Filename: query.Get("filename"), ContentType: kind, SizeBytes: size, SHA256: hex.EncodeToString(hash.Sum(nil)), Status: "queued", Variants: []any{}}
var created, updated time.Time
if err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,status) VALUES($1,$2,$3,$4,$5,$6,$7,$8,'queued') RETURNING created_at,updated_at`, id, chatID, uid, att.Filename, key, kind, size, att.SHA256).Scan(&created, &updated); err != nil {
return response{}, unavailable()
}
if _, err = tx.Exec(ctx, `DELETE FROM attachment_uploads WHERE id=$1`, id); err != nil {
return response{}, unavailable()
}
maxAttempts := 5
if raw := os.Getenv("JOB_MAX_ATTEMPTS"); raw != "" {
n, parseErr := strconv.Atoi(raw)
if parseErr != nil || n < 1 || n > 20 {
return response{}, unavailable()
}
maxAttempts = n
}
parent, state := telemetry.Inject(ctx)
if _, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,staging_key,max_attempts,traceparent,tracestate,request_id) VALUES($1,$2,$3,$4,$5,$6,$7)`, id, id, key, maxAttempts, parent, state, telemetry.RequestID(ctx)); err != nil {
return response{}, unavailable()
}
if _, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id) VALUES($1)`, id); err != nil {
return response{}, unavailable()
}
if err = tx.Commit(ctx); err != nil {
return response{}, unavailable()
}
att.CreatedAt = formatTime(created)
att.UpdatedAt = formatTime(updated)
return response{status: 202, body: att}, nil
}
func validateImage(r io.Reader) *apiError {
_, _, err := image.Decode(r)
if err != nil {
return invalidImage()
}
return nil
}
func (a *API) getAttachment(r *http.Request, uid, id string, content bool) (response, *apiError) {
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return response{}, bad("Неверные параметры вложения")
}
if (!content && len(query) > 0) || (content && (len(query) > 1 || (len(query) > 0 && len(query["variant"]) != 1))) {
return response{}, bad("Неверные параметры вложения")
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
att := Attachment{Variants: []any{}}
var key string
var variantsJSON []byte
var created, updated time.Time
err = a.db.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.owner_id::text,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,a.created_at,a.updated_at,a.variants,a.error_code FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id AND cm.user_id=$2 WHERE a.id=$1`, id, uid).Scan(&att.ID, &att.ChatID, &att.OwnerID, &att.Filename, &key, &att.ContentType, &att.SizeBytes, &att.SHA256, &att.Status, &created, &updated, &variantsJSON, &att.ErrorCode)
if errors.Is(err, pgx.ErrNoRows) {
return response{}, missing()
}
if err != nil {
return response{}, unavailable()
}
_ = json.Unmarshal(variantsJSON, &att.Variants)
att.CreatedAt = formatTime(created)
att.UpdatedAt = formatTime(updated)
if !content {
return response{status: 200, body: att}, nil
}
if att.Status != "ready" {
return response{}, &apiError{status: 409, code: "conflict", message: "Вложение не готово"}
}
if variant, ok := query["variant"]; ok && variant[0] != "original" {
found := false
for _, item := range att.Variants {
v, ok := item.(map[string]any)
if ok && v["name"] == variant[0] {
key = "variants/" + id + "/v1/" + variant[0]
att.ContentType = v["content_type"].(string)
att.SizeBytes = int64(v["size_bytes"].(float64))
att.Filename = variant[0] + map[bool]string{true: ".webp", false: ".jpg"}[variant[0] == "optimized"]
found = true
break
}
}
if !found {
return response{}, missing()
}
}
downloadCtx, downloadCancel := context.WithTimeout(r.Context(), 45*time.Second)
object, err := a.objects.Get(downloadCtx, key)
if err != nil {
downloadCancel()
return response{}, unavailable()
}
return response{status: 200, content: object, contentType: att.ContentType, length: att.SizeBytes, filename: att.Filename, cancel: downloadCancel}, nil
}
+118
View File
@@ -0,0 +1,118 @@
package messenger
import (
"context"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/minio/minio-go/v7"
"mtusi-messenger/internal/objectstore"
)
type CleanupResult struct {
RemovedObjects int `json:"removed_objects"`
RemovedIntents int64 `json:"removed_intents"`
KeptReady int `json:"kept_ready"`
SkippedRecent int `json:"skipped_recent"`
SkippedBusy int `json:"skipped_busy"`
}
// Cleanup removes abandoned uploads. Accepted pipeline jobs protect staging.
func Cleanup(ctx context.Context, db *pgxpool.Pool, store *objectstore.Store, grace time.Duration) (CleanupResult, error) {
result := CleanupResult{}
cutoff := time.Now().Add(-grace)
clean := func(key string) error {
if !strings.HasPrefix(key, "originals/") && !strings.HasPrefix(key, "staging/") {
return nil
}
tx, err := db.Begin(ctx)
if err != nil {
return err
}
defer rollbackUpload(tx)
var locked bool
if err = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,4))`, key).Scan(&locked); err != nil {
return err
}
if !locked {
result.SkippedBusy++
return nil
}
var ready, recent bool
if err = tx.QueryRow(ctx, `SELECT (EXISTS(SELECT 1 FROM attachments WHERE object_key=$1) OR EXISTS(SELECT 1 FROM attachment_jobs WHERE staging_key=$1)),EXISTS(SELECT 1 FROM attachment_uploads WHERE object_key=$1 AND created_at>$2)`, key, cutoff).Scan(&ready, &recent); err != nil {
return err
}
if ready {
result.KeptReady++
return nil
}
if recent {
result.SkippedRecent++
return nil
}
info, err := store.Client.StatObject(ctx, store.Bucket, key, minio.StatObjectOptions{})
exists := err == nil
if err != nil && minio.ToErrorResponse(err).Code != "NoSuchKey" {
return err
}
if exists && info.LastModified.After(cutoff) {
result.SkippedRecent++
return nil
}
if exists {
if err = store.Delete(ctx, key); err != nil {
return err
}
}
command, err := tx.Exec(ctx, `DELETE FROM attachment_uploads WHERE object_key=$1`, key)
if err != nil {
return err
}
if err = tx.Commit(ctx); err != nil {
return err
}
result.RemovedIntents += command.RowsAffected()
if exists {
result.RemovedObjects++
}
return nil
}
rows, err := db.Query(ctx, `SELECT object_key FROM attachment_uploads WHERE created_at<$1 ORDER BY created_at LIMIT 1000`, cutoff)
if err != nil {
return result, err
}
keys := []string{}
for rows.Next() {
var key string
if err = rows.Scan(&key); err != nil {
rows.Close()
return result, err
}
keys = append(keys, key)
}
err = rows.Err()
rows.Close()
if err != nil {
return result, err
}
for _, key := range keys {
if err = clean(key); err != nil {
return result, err
}
}
listctx, cancel := context.WithCancel(ctx)
defer cancel()
for object := range store.Client.ListObjects(listctx, store.Bucket, minio.ListObjectsOptions{Recursive: true}) {
if object.Err != nil {
return result, fmt.Errorf("S3 cleanup listing: %w", object.Err)
}
if object.LastModified.Before(cutoff) {
if err = clean(object.Key); err != nil {
return result, err
}
}
}
return result, nil
}
+82
View File
@@ -0,0 +1,82 @@
package messenger
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"strconv"
"strings"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/scrypt"
)
const scryptN, scryptR, scryptP = 32768, 8, 1
const argonMemory, argonTime, argonThreads = 19456, 2, 1
var passwordSlots = make(chan struct{}, 2)
// concurrency is process-local; Redis rate budget is shared.
func hashPassword(password string) (string, error) {
passwordSlots <- struct{}{}
defer func() { <-passwordSlots }()
salt := make([]byte, 16)
if _, e := rand.Read(salt); e != nil {
return "", e
}
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, 32)
b64 := base64.RawStdEncoding
return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s", argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(hash)), nil
}
func needsRehash(encoded string) bool {
return !strings.HasPrefix(encoded, "$argon2id$v=19$m=19456,t=2,p=1$")
}
func verifyArgon(encoded, password string) bool {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" {
return false
}
var m, t, p uint32
if _, e := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &m, &t, &p); e != nil {
return false
}
if m < 19456 || m > 65536 || t < 2 || t > 4 || p < 1 || p > 4 {
return false
}
salt, e := base64.RawStdEncoding.DecodeString(parts[4])
if e != nil || len(salt) != 16 {
return false
}
expected, e := base64.RawStdEncoding.DecodeString(parts[5])
if e != nil || len(expected) != 32 {
return false
}
actual := argon2.IDKey([]byte(password), salt, t, m, uint8(p), 32)
return subtle.ConstantTimeCompare(actual, expected) == 1
}
func verifyPassword(encoded, password string) bool {
passwordSlots <- struct{}{}
defer func() { <-passwordSlots }()
if strings.HasPrefix(encoded, "$argon2id$") {
return verifyArgon(encoded, password)
}
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[0] != "scrypt" {
return false
}
n, e1 := strconv.Atoi(parts[1])
r, e2 := strconv.Atoi(parts[2])
p, e3 := strconv.Atoi(parts[3])
salt, e4 := base64.RawStdEncoding.DecodeString(parts[4])
expected, e5 := base64.RawStdEncoding.DecodeString(parts[5])
if e1 != nil || e2 != nil || e3 != nil || e4 != nil || e5 != nil || len(expected) != 32 {
return false
}
if n != scryptN || r != scryptR || p != scryptP || len(salt) != 16 {
return false
}
actual, err := scrypt.Key([]byte(password), salt, n, r, p, len(expected))
return err == nil && subtle.ConstantTimeCompare(actual, expected) == 1
}
+44
View File
@@ -0,0 +1,44 @@
package messenger
import (
"strings"
"testing"
)
func TestPasswordHash(t *testing.T) {
const password = "long-test-password"
first, err := hashPassword(password)
if err != nil {
t.Fatal(err)
}
second, err := hashPassword(password)
if err != nil {
t.Fatal(err)
}
if first == password || strings.Contains(first, password) {
t.Fatal("hash contains the original password")
}
if first == second {
t.Fatal("independent hashes must use different salts")
}
if !verifyPassword(first, password) {
t.Fatal("correct password was rejected")
}
if verifyPassword(first, "wrong-test-password") {
t.Fatal("wrong password was accepted")
}
if verifyPassword("damaged-hash", password) {
t.Fatal("malformed hash was accepted")
}
}
func TestArgonParametersAndLegacyBounds(t *testing.T) {
encoded,err:=hashPassword("legacy-password");if err!=nil{t.Fatal(err)}
if !strings.HasPrefix(encoded,"$argon2id$v=19$m=19456,t=2,p=1$"){t.Fatal("wrong Argon2id parameters")}
if needsRehash(encoded){t.Fatal("new hash marked obsolete")}
if !needsRehash("scrypt$32768$8$1$invalid$invalid"){t.Fatal("legacy not marked for upgrade")}
if verifyPassword("$argon2id$v=19$m=4294967295,t=2,p=1$bad$bad","x"){t.Fatal("unbounded cost accepted")}
}
func BenchmarkArgon2id(b *testing.B) {
for i:=0;i<b.N;i++ {if _,e:=hashPassword("synthetic-benchmark-password");e!=nil{b.Fatal(e)}}
}
+39
View File
@@ -0,0 +1,39 @@
package messenger
import (
"crypto/sha256"
"fmt"
"net/http"
)
// A global atomic Redis budget across API replicas bounds expensive login work.
// No attacker-controlled IP or username can bypass the global ceiling.
func (a *API) loginLimit(r *http.Request) *apiError {
ctx, cancel := a.dbContext(r.Context())
defer cancel()
username, _, _ := r.BasicAuth()
sum := sha256.Sum256([]byte(username))
script := `local n=redis.call('INCR',KEYS[1]); if n==1 then redis.call('EXPIRE',KEYS[1],60) end; local u=redis.call('INCR',KEYS[2]); if u==1 then redis.call('EXPIRE',KEYS[2],60) end; if n>120 or u>10 then return 0 end; return 1`
n, e := a.sessions.Eval(ctx, script, []string{"login:global", fmt.Sprintf("login:credential:%x", sum)}).Int()
if e != nil {
return unavailable()
}
if n == 0 {
return &apiError{status: 429, code: "rate_limited", message: "Слишком много попыток входа"}
}
return nil
}
func (a *API) registrationLimit(r *http.Request) *apiError {
ctx, cancel := a.dbContext(r.Context())
defer cancel()
script := `local n=redis.call('INCR',KEYS[1]); if n==1 then redis.call('EXPIRE',KEYS[1],60) end; return n`
n, e := a.sessions.Eval(ctx, script, []string{"login:global"}).Int()
if e != nil {
return unavailable()
}
if n > 120 {
return &apiError{status: 429, code: "rate_limited", message: "Слишком много запросов"}
}
return nil
}
+814
View File
@@ -0,0 +1,814 @@
package messenger
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"mime"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"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"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
"mtusi-messenger/internal/objectstore"
"mtusi-messenger/internal/security"
"mtusi-messenger/internal/telemetry"
)
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 {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User User `json:"user"`
}
type API struct {
objects *objectstore.Store
uploadSlots chan struct{}
db *pgxpool.Pool
sessions *redis.Client
ttl time.Duration
idempotencyTTL time.Duration
dbTimeout time.Duration
instanceID string
logger *log.Logger
}
func NewHandler(db *pgxpool.Pool, sessions *redis.Client, objects *objectstore.Store, ttl, idempotencyTTL, dbTimeout time.Duration, instanceID string, logger *log.Logger) http.Handler {
return &API{db: db, sessions: sessions, objects: objects, uploadSlots: make(chan struct{}, 1), ttl: ttl, idempotencyTTL: idempotencyTTL, dbTimeout: dbTimeout, instanceID: instanceID, logger: logger}
}
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}$`)
var idempotencyKeyRE = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
type apiError struct {
status int
code, message, challenge string
}
type response struct {
status int
body any
noBody bool
content io.ReadCloser
contentType string
length int64
filename string
cancel context.CancelFunc
}
func bad(msg string) *apiError { return &apiError{status: 400, code: "invalid_request", message: msg} }
func missing() *apiError {
return &apiError{status: 404, code: "not_found", message: "Объект не найден"}
}
func unavailable() *apiError {
return &apiError{status: 503, code: "unavailable", message: "Сервис временно недоступен"}
}
func unauthorized(scheme string) *apiError {
challenge := `Bearer realm="messenger"`
if scheme == "Basic" {
challenge = `Basic realm="messenger", charset="UTF-8"`
}
return &apiError{status: 401, code: "unauthorized", message: "Неверные учётные данные", challenge: challenge}
}
func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 && !strings.HasPrefix(r.URL.Path, "/health/") {
lb := false
for _, san := range r.TLS.PeerCertificates[0].DNSNames {
if san == "lb" {
lb = true
}
}
if !lb {
http.Error(w, "client identity denied", http.StatusForbidden)
return
}
}
id := newID()
route, method := telemetry.Route(r.URL.Path), telemetry.Method(r.Method)
parent := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
ctx, span := telemetry.Span(parent, method+" "+route, trace.SpanKindServer, attribute.String("http.route", route), attribute.String("http.request.method", method), attribute.String("request.id", id))
ctx = telemetry.WithRequestID(ctx, id)
r = r.WithContext(ctx)
w.Header().Set("X-Trace-Id", span.SpanContext().TraceID().String())
w.Header().Set("X-Request-Id", id)
w.Header().Set("X-Instance-Id", a.instanceID)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
start, status := time.Now(), 500
defer func() {
if x := recover(); x != nil {
status = 500
telemetry.Event(ctx, "http.panic", nil)
writeError(w, id, &apiError{status: 500, code: "internal_error", message: "Внутренняя ошибка"})
}
span.SetAttributes(attribute.Int("http.response.status_code", status))
if status >= 500 {
span.SetStatus(codes.Error, "HTTP server error")
}
telemetry.HTTP(ctx, method, route, status, time.Since(start))
telemetry.Event(ctx, "http.request", map[string]any{"method": method, "route": route, "status": status, "duration_ms": time.Since(start).Milliseconds()})
span.End()
}()
var res response
var apiErr *apiError
if !security.Valid() && r.URL.Path != "/health/live" {
apiErr = unavailable()
} else {
res, apiErr = a.route(r)
}
if apiErr != nil {
status = apiErr.status
if status == 429 {
w.Header().Set("Retry-After", "60")
}
writeError(w, id, apiErr)
return
}
status = res.status
if res.content != nil {
if res.cancel != nil {
defer res.cancel()
}
defer res.content.Close()
w.Header().Set("Content-Type", res.contentType)
w.Header().Set("Content-Length", strconv.FormatInt(res.length, 10))
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": res.filename}))
w.Header().Set("Cache-Control", "private, no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
if _, err := io.Copy(w, res.content); err != nil {
telemetry.Event(ctx, "http.download_interrupted", nil)
}
return
}
w.WriteHeader(status)
if !res.noBody {
_ = json.NewEncoder(w).Encode(res.body)
}
}
func writeError(w http.ResponseWriter, requestID string, e *apiError) {
if e.challenge != "" {
w.Header().Set("WWW-Authenticate", e.challenge)
}
w.WriteHeader(e.status)
_ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": e.code, "message": e.message, "request_id": requestID}})
}
func decode(r *http.Request, dst any) *apiError {
if strings.ToLower(strings.TrimSpace(strings.Split(r.Header.Get("Content-Type"), ";")[0])) != "application/json" {
return &apiError{status: 415, code: "unsupported_media_type", message: "Требуется application/json"}
}
if r.ContentLength > 1<<20 {
return &apiError{status: 413, code: "payload_too_large", message: "Слишком большой запрос"}
}
data, err := io.ReadAll(io.LimitReader(r.Body, (1<<20)+1))
if err != nil {
return bad("Не удалось прочитать JSON")
}
if len(data) > 1<<20 {
return &apiError{status: 413, code: "payload_too_large", message: "Слишком большой запрос"}
}
if !utf8.Valid(data) {
return bad("JSON должен быть в UTF-8")
}
var fields map[string]json.RawMessage
if json.Unmarshal(data, &fields) == nil {
for _, value := range fields {
if bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
return bad("Поля запроса не должны быть null")
}
}
}
d := json.NewDecoder(bytes.NewReader(data))
d.DisallowUnknownFields()
if err = d.Decode(dst); err != nil {
return bad("Неверный JSON или поля")
}
var rest any
if !errors.Is(d.Decode(&rest), io.EOF) {
return bad("Ожидался один JSON-объект")
}
return nil
}
func validText(s string, max int) bool {
return utf8.ValidString(s) && strings.TrimSpace(s) != "" && utf8.RuneCountInString(s) <= max
}
func validPassword(s string) bool {
n := utf8.RuneCountInString(s)
return utf8.ValidString(s) && n >= 12 && n <= 128
}
func formatTime(t time.Time) string { return t.UTC().Format(time.RFC3339Nano) }
func newID() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
panic(err)
}
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:])
}
func newToken() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return base64.RawURLEncoding.EncodeToString(b)
}
func tokenKey(token string) string {
sum := sha256.Sum256([]byte(token))
return "session:" + hex.EncodeToString(sum[:])
}
func cursorFor(resource string, created time.Time, id string) string {
b, _ := json.Marshal([]string{resource, formatTime(created), id})
return base64.RawURLEncoding.EncodeToString(b)
}
func parsePage(r *http.Request, resource string) (int, *time.Time, string, *apiError) {
q, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return 0, nil, "", bad("Неверные параметры страницы")
}
for k, v := range q {
if (k != "limit" && k != "cursor") || len(v) != 1 {
return 0, nil, "", bad("Неверные параметры страницы")
}
}
limit := 50
if raw := q.Get("limit"); raw != "" {
n, e := strconv.Atoi(raw)
if e != nil || n < 1 || n > 100 {
return 0, nil, "", bad("limit должен быть от 1 до 100")
}
limit = n
} else if _, ok := q["limit"]; ok {
return 0, nil, "", bad("Пустой limit")
}
if _, ok := q["cursor"]; !ok {
return limit, nil, "", nil
}
raw := q.Get("cursor")
if raw == "" || len(raw) > 1024 {
return 0, nil, "", bad("Неверный cursor")
}
b, e := base64.RawURLEncoding.DecodeString(raw)
if e != nil {
return 0, nil, "", bad("Неверный cursor")
}
var p []string
if json.Unmarshal(b, &p) != nil || len(p) != 3 || p[0] != resource || !uuidRE.MatchString(p[2]) {
return 0, nil, "", bad("Неверный cursor")
}
t, e := time.Parse(time.RFC3339Nano, p[1])
if e != nil {
return 0, nil, "", bad("Неверный cursor")
}
return limit, &t, p[2], nil
}
func (a *API) dbContext(parent context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(parent, a.dbTimeout)
}
func (a *API) authenticate(r *http.Request) (string, string, *apiError) {
h := r.Header.Get("Authorization")
if !strings.HasPrefix(h, "Bearer ") || strings.TrimSpace(strings.TrimPrefix(h, "Bearer ")) == "" {
return "", "", unauthorized("Bearer")
}
token := strings.TrimSpace(strings.TrimPrefix(h, "Bearer "))
ctx, cancel := context.WithTimeout(r.Context(), a.dbTimeout)
defer cancel()
uid, err := a.sessions.Get(ctx, tokenKey(token)).Result()
if errors.Is(err, redis.Nil) {
return "", "", unauthorized("Bearer")
}
if err != nil {
a.logger.Printf("session store unavailable: %v", err)
return "", "", unavailable()
}
if !uuidRE.MatchString(uid) {
return "", "", unauthorized("Bearer")
}
return uid, token, nil
}
func scanUser(row pgx.Row) (User, string, error) {
var u User
var created time.Time
var password string
err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &created, &password)
u.CreatedAt = formatTime(created)
return u, password, err
}
func (a *API) route(r *http.Request) (response, *apiError) {
p := r.URL.Path
if r.Method == "GET" && p == "/health/live" {
return response{status: 200, body: map[string]string{"status": "ok"}}, nil
}
if r.Method == "GET" && p == "/health/ready" {
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
defer cancel()
dbctx, dbspan := telemetry.Span(ctx, "db.readiness", trace.SpanKindClient, attribute.String("db.system.name", "postgresql"))
dbErr := a.db.Ping(dbctx)
telemetry.Result(dbspan, dbErr)
if dbErr != nil || a.sessions.Ping(ctx).Err() != nil || a.objects.Ready(ctx) != nil {
return response{}, unavailable()
}
return response{status: 200, body: map[string]string{"status": "ok"}}, nil
}
if r.Method == "POST" && p == "/api/v1/users" {
return a.createUser(r)
}
if r.Method == "POST" && p == "/api/v1/auth/sessions" {
return a.createSession(r)
}
if !strings.HasPrefix(p, "/api/v1/") {
return response{}, missing()
}
uid, token, authErr := a.authenticate(r)
if authErr != nil {
return response{}, authErr
}
if r.Method == "DELETE" && p == "/api/v1/auth/sessions/current" {
ctx, cancel := context.WithTimeout(r.Context(), a.dbTimeout)
defer cancel()
if err := a.sessions.Del(ctx, tokenKey(token)).Err(); err != nil {
return response{}, unavailable()
}
return response{status: 204, noBody: true}, nil
}
if r.Method == "GET" && p == "/api/v1/users/me" {
return a.currentUser(r, uid)
}
if strings.HasPrefix(p, "/api/v1/attachments/") {
parts := strings.Split(strings.TrimPrefix(p, "/api/v1/attachments/"), "/")
if !uuidRE.MatchString(parts[0]) {
return response{}, bad("Неверный attachment_id")
}
if r.Method == "GET" && (len(parts) == 1 || (len(parts) == 2 && parts[1] == "content")) {
return a.getAttachment(r, uid, parts[0], len(parts) == 2)
}
return response{}, missing()
}
if p == "/api/v1/chats" {
if r.Method == "POST" {
return a.createChat(r, uid)
}
if r.Method == "GET" {
return a.listChats(r, uid)
}
}
if !strings.HasPrefix(p, "/api/v1/chats/") {
return response{}, missing()
}
parts := strings.Split(strings.TrimPrefix(p, "/api/v1/chats/"), "/")
if len(parts) < 1 || !uuidRE.MatchString(parts[0]) {
return response{}, bad("Неверный chat_id")
}
chatID := parts[0]
if len(parts) == 2 && parts[1] == "attachments" && r.Method == "POST" {
return a.uploadAttachment(r, uid, chatID)
}
if len(parts) == 1 && r.Method == "GET" {
return a.getChat(r, uid, chatID)
}
if len(parts) == 2 && parts[1] == "messages" {
if r.Method == "POST" {
return a.createMessage(r, uid, chatID)
}
if r.Method == "GET" {
return a.listMessages(r, uid, chatID)
}
}
return response{}, missing()
}
func (a *API) createUser(r *http.Request) (response, *apiError) {
var in struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
if e := decode(r, &in); e != nil {
return response{}, e
}
if !usernameRE.MatchString(in.Username) || !validText(in.DisplayName, 100) || !validPassword(in.Password) {
return response{}, bad("Неверные данные пользователя")
}
if e := a.registrationLimit(r); e != nil {
return response{}, e
}
passwordHash, err := hashPassword(in.Password)
if err != nil {
return response{}, &apiError{status: 500, code: "internal_error", message: "Внутренняя ошибка"}
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
var u User
var created time.Time
err = a.db.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4) RETURNING id::text,username,display_name,created_at`, newID(), in.Username, in.DisplayName, passwordHash).Scan(&u.ID, &u.Username, &u.DisplayName, &created)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return response{}, &apiError{status: 409, code: "conflict", message: "Имя пользователя занято"}
}
return response{}, unavailable()
}
u.CreatedAt = formatTime(created)
return response{status: 201, body: u}, nil
}
func (a *API) createSession(r *http.Request) (response, *apiError) {
if e := a.loginLimit(r); e != nil {
return response{}, e
}
if r.ContentLength > 0 {
return response{}, bad("Тело запроса не допускается")
}
h := r.Header.Get("Authorization")
if !strings.HasPrefix(h, "Basic ") {
return response{}, unauthorized("Basic")
}
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(strings.TrimPrefix(h, "Basic ")))
if err != nil {
return response{}, unauthorized("Basic")
}
parts := strings.SplitN(string(raw), ":", 2)
if len(parts) != 2 || !usernameRE.MatchString(parts[0]) {
return response{}, unauthorized("Basic")
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
u, passwordHash, err := scanUser(a.db.QueryRow(ctx, `SELECT id::text,username,display_name,created_at,password_hash FROM users WHERE username=$1`, parts[0]))
if errors.Is(err, pgx.ErrNoRows) {
return response{}, unauthorized("Basic")
}
if err != nil {
return response{}, unavailable()
}
if !verifyPassword(passwordHash, parts[1]) {
return response{}, unauthorized("Basic")
}
if needsRehash(passwordHash) {
upgraded, e := hashPassword(parts[1])
if e != nil {
return response{}, unavailable()
}
if _, e = a.db.Exec(ctx, `UPDATE users SET password_hash=$1 WHERE id=$2 AND password_hash=$3`, upgraded, u.ID, passwordHash); e != nil {
return response{}, unavailable()
}
}
token := newToken()
expires := time.Now().UTC().Add(a.ttl)
if err = a.sessions.Set(ctx, tokenKey(token), u.ID, a.ttl).Err(); err != nil {
return response{}, unavailable()
}
return response{status: 201, body: Session{Token: token, TokenType: "Bearer", ExpiresAt: formatTime(expires), User: u}}, nil
}
func (a *API) currentUser(r *http.Request, uid string) (response, *apiError) {
ctx, cancel := a.dbContext(r.Context())
defer cancel()
u, _, err := scanUser(a.db.QueryRow(ctx, `SELECT id::text,username,display_name,created_at,password_hash FROM users WHERE id=$1`, uid))
if errors.Is(err, pgx.ErrNoRows) {
return response{}, unauthorized("Bearer")
}
if err != nil {
return response{}, unavailable()
}
return response{status: 200, body: u}, nil
}
func (a *API) createChat(r *http.Request, uid string) (response, *apiError) {
var in struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
if e := decode(r, &in); e != nil {
return response{}, e
}
if !validText(in.Title, 100) || len(in.MemberIDs) < 1 || len(in.MemberIDs) > 100 {
return response{}, bad("Неверные данные чата")
}
seen := map[string]bool{}
for _, id := range in.MemberIDs {
if !uuidRE.MatchString(id) || seen[id] {
return response{}, bad("Неверные участники чата")
}
seen[id] = true
}
if !seen[uid] {
return response{}, bad("Создатель должен быть участником")
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
tx, err := a.db.Begin(ctx)
if err != nil {
return response{}, unavailable()
}
defer tx.Rollback(ctx)
c := Chat{ID: newID(), Title: in.Title, MemberIDs: append([]string{}, in.MemberIDs...)}
var created time.Time
if err = tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at`, c.ID, c.Title).Scan(&created); err != nil {
return response{}, unavailable()
}
for _, id := range c.MemberIDs {
if _, err = tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)`, c.ID, id); err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23503" {
return response{}, bad("Неверные участники чата")
}
return response{}, unavailable()
}
}
if err = tx.Commit(ctx); err != nil {
return response{}, unavailable()
}
c.CreatedAt = formatTime(created)
return response{status: 201, body: c}, nil
}
func scanChat(row pgx.Row) (Chat, time.Time, error) {
var c Chat
var t time.Time
err := row.Scan(&c.ID, &c.Title, &c.MemberIDs, &t)
c.CreatedAt = formatTime(t)
return c, t, err
}
func chatSelect() string {
return `SELECT c.id::text,c.title,ARRAY(SELECT cm2.user_id::text FROM chat_members cm2 WHERE cm2.chat_id=c.id ORDER BY cm2.user_id),c.created_at FROM chats c`
}
func (a *API) getChat(r *http.Request, uid, chatID string) (response, *apiError) {
ctx, cancel := a.dbContext(r.Context())
defer cancel()
c, _, err := scanChat(a.db.QueryRow(ctx, chatSelect()+` WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members cm WHERE cm.chat_id=c.id AND cm.user_id=$2)`, chatID, uid))
if errors.Is(err, pgx.ErrNoRows) {
return response{}, missing()
}
if err != nil {
return response{}, unavailable()
}
return response{status: 200, body: c}, nil
}
func (a *API) listChats(r *http.Request, uid string) (response, *apiError) {
limit, afterTime, afterID, e := parsePage(r, "chats:"+uid)
if e != nil {
return response{}, e
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
if afterTime != nil {
var ok bool
err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 AND c.id=$2 AND c.created_at=$3)`, uid, afterID, *afterTime).Scan(&ok)
if err != nil {
return response{}, unavailable()
}
if !ok {
return response{}, bad("Неверный cursor")
}
}
var rows pgx.Rows
var err error
base := chatSelect() + ` JOIN chat_members mine ON mine.chat_id=c.id WHERE mine.user_id=$1`
if afterTime == nil {
rows, err = a.db.Query(ctx, base+` ORDER BY c.created_at,c.id LIMIT $2`, uid, limit+1)
} else {
rows, err = a.db.Query(ctx, base+` AND (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, uid, *afterTime, afterID, limit+1)
}
if err != nil {
return response{}, unavailable()
}
defer rows.Close()
items := make([]Chat, 0, limit+1)
times := make([]time.Time, 0, limit+1)
for rows.Next() {
c, t, scanErr := scanChat(rows)
if scanErr != nil {
return response{}, unavailable()
}
items = append(items, c)
times = append(times, t)
}
if rows.Err() != nil {
return response{}, unavailable()
}
var next any
if len(items) > limit {
last := items[limit-1]
next = cursorFor("chats:"+uid, times[limit-1], last.ID)
items = items[:limit]
}
return response{status: 200, body: map[string]any{"items": items, "next_cursor": next}}, nil
}
func (a *API) createMessage(r *http.Request, uid, chatID string) (response, *apiError) {
key := r.Header.Get("Idempotency-Key")
if !idempotencyKeyRE.MatchString(key) {
return response{}, bad("Требуется корректный Idempotency-Key")
}
var in struct {
Text *string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
if e := decode(r, &in); e != nil {
return response{}, e
}
if in.Text == nil {
return response{}, bad("Требуется поле text")
}
text := *in.Text
if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 4000 || len(in.AttachmentIDs) > 10 || (strings.TrimSpace(text) == "" && len(in.AttachmentIDs) == 0) {
return response{}, bad("Текст сообщения должен содержать от 1 до 4000 символов")
}
if in.AttachmentIDs == nil {
in.AttachmentIDs = []string{}
}
seen := map[string]bool{}
for i, id := range in.AttachmentIDs {
id = strings.ToLower(id)
if !uuidRE.MatchString(id) || seen[id] {
return response{}, bad("Неверные attachment_ids")
}
seen[id] = true
in.AttachmentIDs[i] = id
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
tx, err := a.db.Begin(ctx)
if err != nil {
return response{}, unavailable()
}
defer tx.Rollback(ctx)
var member bool
if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`, chatID, uid).Scan(&member); err != nil {
return response{}, unavailable()
}
if !member {
return response{}, missing()
}
requestHash := sha256.Sum256([]byte(text))
if len(in.AttachmentIDs) > 0 {
canonical, _ := json.Marshal(in)
requestHash = sha256.Sum256(canonical)
}
if _, err = tx.Exec(ctx, `DELETE FROM message_idempotency WHERE user_id=$1 AND method=$2 AND path=$3 AND idempotency_key=$4 AND created_at < clock_timestamp() - ($5 * interval '1 second')`, uid, r.Method, r.URL.Path, key, int64(a.idempotencyTTL/time.Second)); err != nil {
return response{}, unavailable()
}
result, err := tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,method,path,idempotency_key,request_hash) VALUES($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING`, uid, r.Method, r.URL.Path, key, requestHash[:])
if err != nil {
return response{}, unavailable()
}
inserted := result.RowsAffected() == 1
if !inserted {
var storedHash []byte
var messageID string
if err = tx.QueryRow(ctx, `SELECT request_hash,message_id::text FROM message_idempotency WHERE user_id=$1 AND method=$2 AND path=$3 AND idempotency_key=$4 FOR UPDATE`, uid, r.Method, r.URL.Path, key).Scan(&storedHash, &messageID); err != nil {
return response{}, unavailable()
}
if !bytes.Equal(storedHash, requestHash[:]) {
return response{}, &apiError{status: 409, code: "conflict", message: "Idempotency-Key уже использован с другим запросом"}
}
var m Message
var created time.Time
if err = tx.QueryRow(ctx, `SELECT id::text,chat_id::text,sender_id::text,text,created_at,attachment_ids::text[] FROM messages WHERE id=$1`, messageID).Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &created, &m.AttachmentIDs); err != nil {
return response{}, unavailable()
}
m.CreatedAt = formatTime(created)
if err = tx.Commit(ctx); err != nil {
return response{}, unavailable()
}
return response{status: 201, body: m}, nil
}
for _, id := range in.AttachmentIDs {
var state string
err = tx.QueryRow(ctx, `SELECT status FROM attachments WHERE id=$1 AND chat_id=$2`, id, chatID).Scan(&state)
if errors.Is(err, pgx.ErrNoRows) {
return response{}, missing()
}
if err != nil {
return response{}, unavailable()
}
if state == "failed" {
return response{}, &apiError{status: 409, code: "conflict", message: "Вложение не готово"}
}
}
m := Message{ID: newID(), ChatID: chatID, SenderID: uid, Text: text, AttachmentIDs: in.AttachmentIDs}
var created time.Time
if err = tx.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,attachment_ids) VALUES($1,$2,$3,$4,$5) RETURNING created_at`, m.ID, m.ChatID, m.SenderID, m.Text, m.AttachmentIDs).Scan(&created); err != nil {
return response{}, unavailable()
}
if _, err = tx.Exec(ctx, `UPDATE message_idempotency SET message_id=$1 WHERE user_id=$2 AND method=$3 AND path=$4 AND idempotency_key=$5`, m.ID, uid, r.Method, r.URL.Path, key); err != nil {
return response{}, unavailable()
}
if err = tx.Commit(ctx); err != nil {
return response{}, unavailable()
}
m.CreatedAt = formatTime(created)
return response{status: 201, body: m}, nil
}
func (a *API) listMessages(r *http.Request, uid, chatID string) (response, *apiError) {
limit, afterTime, afterID, e := parsePage(r, "messages:"+chatID)
if e != nil {
return response{}, e
}
ctx, cancel := a.dbContext(r.Context())
defer cancel()
var member bool
if err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`, chatID, uid).Scan(&member); err != nil {
return response{}, unavailable()
}
if !member {
return response{}, missing()
}
if afterTime != nil {
var ok bool
err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM messages WHERE chat_id=$1 AND id=$2 AND created_at=$3)`, chatID, afterID, *afterTime).Scan(&ok)
if err != nil {
return response{}, unavailable()
}
if !ok {
return response{}, bad("Неверный cursor")
}
}
var rows pgx.Rows
var err error
base := `SELECT id::text,chat_id::text,sender_id::text,text,created_at,attachment_ids::text[] FROM messages WHERE chat_id=$1`
if afterTime == nil {
rows, err = a.db.Query(ctx, base+` ORDER BY created_at,id LIMIT $2`, chatID, limit+1)
} else {
rows, err = a.db.Query(ctx, base+` AND (created_at,id)>($2,$3) ORDER BY created_at,id LIMIT $4`, chatID, *afterTime, afterID, limit+1)
}
if err != nil {
return response{}, unavailable()
}
defer rows.Close()
items := make([]Message, 0, limit+1)
times := make([]time.Time, 0, limit+1)
for rows.Next() {
var m Message
var t time.Time
if rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &t, &m.AttachmentIDs) != nil {
return response{}, unavailable()
}
m.CreatedAt = formatTime(t)
items = append(items, m)
times = append(times, t)
}
if rows.Err() != nil {
return response{}, unavailable()
}
var next any
if len(items) > limit {
last := items[limit-1]
next = cursorFor("messages:"+chatID, times[limit-1], last.ID)
items = items[:limit]
}
return response{status: 200, body: map[string]any{"items": items, "next_cursor": next}}, nil
}
+59
View File
@@ -0,0 +1,59 @@
package objectstore
import (
"context"
"encoding/json"
"mtusi-messenger/internal/security"
"net/http"
"net/url"
"strings"
madmin "github.com/minio/madmin-go/v3"
)
// Bootstrap receives root credentials only in the one-shot s3-init process.
// The API and cleaner receive a separate user limited to this bucket/prefix.
func Bootstrap(ctx context.Context, endpoint, bucket, rootAccess, rootSecret, apiAccess, apiSecret, role string) error {
u, err := url.Parse(endpoint)
if err != nil {
return err
}
admin, err := madmin.New(u.Host, rootAccess, rootSecret, u.Scheme == "https")
if err != nil {
return err
}
tc, e := security.ClientTLS()
if e != nil {
return e
}
admin.SetCustomTransport(&http.Transport{TLSClientConfig: tc})
if err = admin.AddUser(ctx, apiAccess, apiSecret); err != nil {
return err
}
statements := []any{map[string]any{"Effect": "Allow", "Action": []string{"s3:GetBucketLocation", "s3:ListBucket"}, "Resource": []string{"arn:aws:s3:::" + bucket}}}
allow := func(actions []string, prefixes ...string) {
resources := []string{}
for _, prefix := range prefixes {
resources = append(resources, "arn:aws:s3:::"+bucket+"/"+prefix+"/*")
}
statements = append(statements, map[string]any{"Effect": "Allow", "Action": actions, "Resource": resources})
}
if strings.HasPrefix(role, "api") {
allow([]string{"s3:PutObject", "s3:GetObject"}, "staging")
allow([]string{"s3:GetObject"}, "originals", "variants")
} else if role == "worker" {
allow([]string{"s3:GetObject"}, "staging")
allow([]string{"s3:GetObject", "s3:PutObject"}, "originals", "variants")
} else if role == "dispatcher" || role == "cleanup" {
allow([]string{"s3:GetObject", "s3:DeleteObject"}, "staging")
}
policy := map[string]any{"Version": "2012-10-17", "Statement": statements}
encoded, err := json.Marshal(policy)
if err != nil {
return err
}
if err = admin.AddCannedPolicy(ctx, "messenger-"+apiAccess, encoded); err != nil {
return err
}
return admin.SetPolicy(ctx, "messenger-"+apiAccess, apiAccess, false)
}
+113
View File
@@ -0,0 +1,113 @@
package objectstore
import (
"context"
"fmt"
"io"
"net"
"net/http"
"net/url"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"mtusi-messenger/internal/security"
"mtusi-messenger/internal/telemetry"
)
type Store struct {
Client *minio.Client
Bucket string
endpoint string
}
func New(endpoint, region, bucket, access, secret string) (*Store, error) {
u, err := url.Parse(endpoint)
if err != nil || u.Host == "" || u.Scheme != "https" || u.Path != "" {
return nil, fmt.Errorf("invalid S3 endpoint")
}
tlsConfig, e := security.ClientTLS()
if e != nil {
return nil, e
}
transport := &http.Transport{TLSClientConfig: tlsConfig,
DialContext: (&net.Dialer{Timeout: 2 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
MaxIdleConns: 16, MaxIdleConnsPerHost: 8, MaxConnsPerHost: 8,
ResponseHeaderTimeout: 10 * time.Second, IdleConnTimeout: 30 * time.Second,
TLSHandshakeTimeout: 3 * time.Second,
}
client, err := minio.New(u.Host, &minio.Options{
Creds: credentials.NewStaticV4(access, secret, ""), Secure: u.Scheme == "https",
Region: region, Transport: transport, MaxRetries: 1,
})
if err != nil {
return nil, err
}
return &Store{Client: client, Bucket: bucket, endpoint: endpoint}, nil
}
func (s *Store) Ready(ctx context.Context) (err error) {
ctx, span := telemetry.Span(ctx, "s3.bucket.exists", trace.SpanKindClient, attribute.String("db.system.name", "s3"))
defer func() { telemetry.Result(span, err) }()
ok, err := s.Client.BucketExists(ctx, s.Bucket)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("S3 bucket missing")
}
return nil
}
func (s *Store) Put(ctx context.Context, key string, r io.Reader, size int64, kind string) (err error) {
ctx, span := telemetry.Span(ctx, "s3.put", trace.SpanKindClient, attribute.String("db.system.name", "s3"))
defer func() { telemetry.Result(span, err) }()
_, err = s.Client.PutObject(ctx, s.Bucket, key, r, size, minio.PutObjectOptions{
ContentType: kind, DisableMultipart: true,
})
return err
}
func (s *Store) Get(ctx context.Context, key string) (object *minio.Object, err error) {
ctx, span := telemetry.Span(ctx, "s3.get", trace.SpanKindClient, attribute.String("db.system.name", "s3"))
defer func() { telemetry.Result(span, err) }()
object, err = s.Client.GetObject(ctx, s.Bucket, key, minio.GetObjectOptions{})
if err != nil {
return nil, err
}
if _, err = object.Stat(); err != nil {
object.Close()
return nil, err
}
return object, nil
}
func (s *Store) Delete(ctx context.Context, key string) (err error) {
ctx, span := telemetry.Span(ctx, "s3.delete", trace.SpanKindClient, attribute.String("db.system.name", "s3"))
defer func() { telemetry.Result(span, err) }()
return s.Client.RemoveObject(ctx, s.Bucket, key, minio.RemoveObjectOptions{})
}
// Audit performs an actual unauthenticated GET and an out-of-scope operation
// with API credentials. Neither check prints credentials or object URLs.
func (s *Store) Audit(ctx context.Context, key string) error {
req, err := http.NewRequestWithContext(ctx, "GET", s.endpoint+"/"+s.Bucket+"/"+key, nil)
if err != nil {
return err
}
response, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
if err != nil {
return err
}
response.Body.Close()
if response.StatusCode != 403 {
return fmt.Errorf("anonymous GET returned %d", response.StatusCode)
}
err = s.Client.MakeBucket(ctx, "forbidden-audit-bucket", minio.MakeBucketOptions{})
if minio.ToErrorResponse(err).Code != "AccessDenied" {
return fmt.Errorf("API credentials are not restricted: %v", err)
}
return nil
}
+549
View File
@@ -0,0 +1,549 @@
// Package pipeline implements durable intent, at-least-once delivery and fenced effects.
package pipeline
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math/rand/v2"
"os"
"os/exec"
"path/filepath"
"strconv"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"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"
"mtusi-messenger/internal/objectstore"
"mtusi-messenger/internal/telemetry"
)
const Stream = "attachment.jobs.v1"
const Group = "image-workers"
type Pipeline struct {
DB *pgxpool.Pool
Broker *redis.Client
Objects *objectstore.Store
Timeout time.Duration
Retention time.Duration
Logger *log.Logger
}
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"`
Created string `json:"created_at"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
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"`
SHA string `json:"sha256"`
}
func (p *Pipeline) Checkpoint(ctx context.Context, point string) {
var armed bool
err := p.DB.QueryRow(ctx, `UPDATE pipeline_faults SET armed=false,hit_at=clock_timestamp() WHERE point=$1 AND armed RETURNING true`, point).Scan(&armed)
if err == nil && armed {
p.Logger.Printf("injected crash: %s", point)
os.Exit(86)
}
}
func pause(ctx context.Context, d time.Duration) {
select {
case <-ctx.Done():
case <-time.After(d):
}
}
// Dispatch re-publishes unfinished intents if a broker confirmation/connection is lost.
// Publication is deliberately outside the PostgreSQL transaction; duplicates are safe.
func (p *Pipeline) Dispatch(ctx context.Context) {
for ctx.Err() == nil {
if err := p.dispatchOnce(ctx); err != nil {
p.Logger.Print("dispatcher unavailable; intent retained")
}
sweepctx, cancelSweep := context.WithTimeout(ctx, 5*time.Second)
if err := p.Sweep(sweepctx); err != nil {
p.Logger.Print("staging sweep deferred")
}
cancelSweep()
pause(ctx, time.Second)
}
}
func (p *Pipeline) dispatchOnce(ctx context.Context) error {
rows, err := p.DB.Query(ctx, `SELECT j.id::text,j.attachment_id::text,j.pipeline_version,j.attempts+1,j.created_at,j.traceparent,j.tracestate
FROM attachment_jobs j JOIN attachment_outbox o ON o.job_id=j.id
WHERE ((j.state='queued' AND j.next_at<=clock_timestamp()) OR (j.state='processing' AND j.lease_until<clock_timestamp()))
AND (o.published_at IS NULL OR o.published_at<clock_timestamp()-interval '5 seconds') ORDER BY j.created_at LIMIT 50`)
if err != nil {
return err
}
jobs := []Job{}
for rows.Next() {
j := Job{SchemaVersion: 1, Type: "attachment.process.v1"}
var created time.Time
if err = rows.Scan(&j.ID, &j.AttachmentID, &j.Version, &j.Attempt, &created, &j.Traceparent, &j.Tracestate); err != nil {
rows.Close()
return err
}
j.Created = created.UTC().Format(time.RFC3339Nano)
jobs = append(jobs, j)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
for _, j := range jobs {
p.Checkpoint(ctx, "dispatcher_before_publish")
parent := telemetry.Extract(ctx, j.Traceparent, j.Tracestate)
pubctx, pubspan := telemetry.Span(parent, "attachment.publish", trace.SpanKindProducer, attribute.String("messaging.system", "redis"), attribute.String("messaging.destination.name", Stream), attribute.Int("job.attempt", j.Attempt))
j.Traceparent, j.Tracestate = telemetry.Inject(pubctx)
b, _ := json.Marshal(j)
err = p.Broker.XAdd(pubctx, &redis.XAddArgs{Stream: Stream, Values: map[string]any{"job": string(b)}}).Err()
telemetry.Event(pubctx, "job.published", map[string]any{"job_id": j.ID, "attempt": j.Attempt, "success": err == nil})
telemetry.Result(pubspan, err)
if err != nil {
return err
}
p.Checkpoint(ctx, "dispatcher_after_publish")
if _, err = p.DB.Exec(ctx, `UPDATE attachment_outbox SET published_at=clock_timestamp(),publications=publications+1 WHERE job_id=$1`, j.ID); err != nil {
return err
}
}
return nil
}
func (p *Pipeline) ack(ctx context.Context, id string) {
// Stream belongs to one group. Delete only after acknowledged; PG remains recovery authority.
if p.Broker.XAck(ctx, Stream, Group, id).Err() == nil {
_ = p.Broker.XDel(ctx, Stream, id).Err()
}
}
func (p *Pipeline) Worker(ctx context.Context, concurrency int) error {
if concurrency < 1 || concurrency > 4 {
return fmt.Errorf("WORKER_CONCURRENCY must be 1..4")
}
// One message at a time per consumer: prefetch=1.
done := make(chan struct{}, concurrency)
for i := 0; i < concurrency; i++ {
go func() { defer func() { done <- struct{}{} }(); p.consume(ctx, uuid.NewString()) }()
}
for i := 0; i < concurrency; i++ {
<-done
}
return nil
}
func (p *Pipeline) consume(ctx context.Context, consumer string) {
reclaimIdle := p.Timeout + 10*time.Second
for ctx.Err() == nil {
_ = p.Broker.XGroupCreateMkStream(ctx, Stream, Group, "0").Err()
pending, _, err := p.Broker.XAutoClaim(ctx, &redis.XAutoClaimArgs{Stream: Stream, Group: Group, Consumer: consumer, MinIdle: reclaimIdle, Start: "0-0", Count: 1}).Result()
if err == nil && len(pending) > 0 {
p.handle(ctx, pending[0])
continue
}
messages, err := p.Broker.XReadGroup(ctx, &redis.XReadGroupArgs{Group: Group, Consumer: consumer, Streams: []string{Stream, ">"}, Count: 1, Block: time.Second}).Result()
if err != nil {
pause(ctx, 200*time.Millisecond)
continue
}
for _, stream := range messages {
for _, m := range stream.Messages {
p.handle(ctx, m)
}
}
}
}
func (p *Pipeline) handle(ctx context.Context, m redis.XMessage) {
raw, ok := m.Values["job"].(string)
var j Job
if !ok || json.Unmarshal([]byte(raw), &j) != nil || j.SchemaVersion != 1 || j.Version != 1 || j.Type != "attachment.process.v1" || uuid.Validate(j.ID) != nil || uuid.Validate(j.AttachmentID) != nil {
// Malformed envelopes go to a diagnostic dead-letter stream, never interpreted as storage paths.
if p.Broker.XAdd(ctx, &redis.XAddArgs{Stream: "attachment.invalid.dlq", Values: map[string]any{"stream_id": m.ID, "error_code": "invalid_envelope"}}).Err() == nil {
p.ack(ctx, m.ID)
}
return
}
ctx = telemetry.Extract(ctx, j.Traceparent, j.Tracestate)
ctx, consumer := telemetry.Span(ctx, "attachment.consume", trace.SpanKindConsumer, attribute.String("messaging.system", "redis"), attribute.String("messaging.destination.name", Stream), attribute.String("job.id", j.ID))
began := time.Now()
attempted := false
outcome := "abandoned"
defer func() {
consumer.SetAttributes(attribute.String("job.outcome", outcome))
if outcome == "retry" || outcome == "failed" || outcome == "abandoned" {
consumer.SetStatus(codes.Error, outcome)
}
if attempted {
telemetry.Busy.Add(-1)
telemetry.Job(ctx, outcome, time.Since(began))
}
telemetry.Event(ctx, "job.completed", map[string]any{"job_id": j.ID, "outcome": outcome, "duration_ms": time.Since(began).Milliseconds()})
consumer.End()
}()
jobctx, cancel := context.WithTimeout(ctx, p.Timeout)
defer cancel()
conn, err := p.DB.Acquire(jobctx)
if err != nil {
return
}
defer conn.Release()
var locked bool
if err = conn.QueryRow(jobctx, `SELECT pg_try_advisory_lock(hashtextextended($1,5))`, j.ID).Scan(&locked); err != nil || !locked {
return
}
defer func() {
unlockctx, done := context.WithTimeout(context.Background(), 3*time.Second)
defer done()
_, e := conn.Exec(unlockctx, `SELECT pg_advisory_unlock(hashtextextended($1,5))`, j.ID)
if e != nil {
_ = conn.Conn().Close(unlockctx)
}
}()
tx, err := conn.Begin(jobctx)
if err != nil {
return
}
defer tx.Rollback(context.Background())
var state, staging, attachment, requestID string
var accepted time.Time
var attempt, maxAttempts int
var due bool
err = tx.QueryRow(jobctx, `SELECT state,staging_key,attachment_id::text,attempts,max_attempts,
(state='queued' AND next_at<=clock_timestamp()) OR (state='processing' AND lease_until<clock_timestamp())
,created_at,request_id FROM attachment_jobs WHERE id=$1 FOR UPDATE`, j.ID).Scan(&state, &staging, &attachment, &attempt, &maxAttempts, &due, &accepted, &requestID)
if errors.Is(err, pgx.ErrNoRows) {
p.ack(ctx, m.ID)
return
}
if err != nil {
return
}
if attachment != j.AttachmentID {
return
}
ctx = telemetry.WithRequestID(ctx, requestID)
jobctx = telemetry.WithRequestID(jobctx, requestID)
if state == "ready" || state == "failed" {
outcome = "duplicate"
_ = tx.Rollback(jobctx)
p.ack(ctx, m.ID)
return
}
if !due {
outcome = "deferred"
_ = tx.Rollback(jobctx)
p.ack(ctx, m.ID)
return
}
if attempt >= maxAttempts {
if p.failTx(jobctx, tx, j.ID, attachment, "retry_exhausted") == nil && tx.Commit(jobctx) == nil {
p.ack(ctx, m.ID)
}
return
}
token := uuid.NewString()
consumer.SetAttributes(attribute.Int("job.attempt", attempt+1))
attempt++
_, err = tx.Exec(jobctx, `UPDATE attachment_jobs SET state='processing',attempts=$2,lease_token=$3,lease_until=clock_timestamp()+($4*interval '1 second'),updated_at=clock_timestamp() WHERE id=$1`, j.ID, attempt, token, int(p.Timeout/time.Second)+5)
if err != nil {
return
}
if _, err = tx.Exec(jobctx, `UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=$1`, attachment); err != nil {
return
}
if tx.Commit(jobctx) != nil {
return
}
attempted = true
telemetry.Busy.Add(1)
telemetry.Event(jobctx, "job.started", map[string]any{"job_id": j.ID, "attempt": attempt})
p.Checkpoint(jobctx, "worker_after_claim")
variants, code := p.process(jobctx, attachment, staging)
p.Checkpoint(jobctx, "worker_after_objects")
// A fresh transaction completes after job timeout/cancel; token fences stale attempts.
finishctx, finishcancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer finishcancel()
finish, err := conn.Begin(finishctx)
if err != nil {
return
}
defer finish.Rollback(context.Background())
var current string
if err = finish.QueryRow(finishctx, `SELECT lease_token::text FROM attachment_jobs WHERE id=$1 AND state='processing' FOR UPDATE`, j.ID).Scan(&current); err != nil || current != token {
return
}
if code == "" {
outcome = "success"
encoded, _ := json.Marshal(variants)
_, err = finish.Exec(finishctx, `UPDATE attachments SET status='ready',object_key=$2,variants=$3,error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, attachment, "originals/"+attachment, encoded)
if err == nil {
_, err = finish.Exec(finishctx, `UPDATE attachment_jobs SET state='ready',lease_until=NULL,lease_token=NULL,error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, j.ID)
}
} else if code == "invalid_image" || attempt >= maxAttempts {
outcome = "failed"
if code != "invalid_image" {
code = "retry_exhausted"
}
err = p.failTx(finishctx, finish, j.ID, attachment, code)
} else {
outcome = "retry"
delay := RetryDelay(attempt)
_, err = finish.Exec(finishctx, `UPDATE attachment_jobs SET state='queued',error_code=$2,next_at=clock_timestamp()+($3*interval '1 millisecond'),lease_until=NULL,lease_token=NULL,updated_at=clock_timestamp() WHERE id=$1`, j.ID, code, delay.Milliseconds())
if err == nil {
_, err = finish.Exec(finishctx, `UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=$1`, attachment)
}
}
if err != nil || finish.Commit(finishctx) != nil {
outcome = "abandoned"
return
}
if outcome == "success" {
telemetry.Ready(ctx, time.Since(accepted))
}
p.Checkpoint(finishctx, "worker_before_ack")
p.ack(finishctx, m.ID)
}
func RetryDelay(attempt int) time.Duration {
if attempt > 6 {
attempt = 6
}
base := time.Second * time.Duration(1<<uint(attempt-1))
return base + time.Duration(rand.Int64N(int64(base/2)+1))
}
func (p *Pipeline) failTx(ctx context.Context, tx pgx.Tx, id, attachment, code string) error {
_, err := tx.Exec(ctx, `UPDATE attachment_jobs SET state='failed',error_code=$2,lease_until=NULL,lease_token=NULL,updated_at=clock_timestamp() WHERE id=$1`, id, code)
if err == nil {
_, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code=$2,updated_at=clock_timestamp() WHERE id=$1`, attachment, code)
}
return err
}
func (p *Pipeline) process(ctx context.Context, id, key string) ([]Variant, string) {
dir, err := os.MkdirTemp("", "job-*")
if err != nil {
return nil, "storage_unavailable"
}
defer os.RemoveAll(dir)
object, err := p.Objects.Get(ctx, key)
if err != nil {
return nil, "storage_unavailable"
}
file, err := os.Create(filepath.Join(dir, "source"))
if err != nil {
object.Close()
return nil, "storage_unavailable"
}
hash := sha256.New()
n, copyErr := io.Copy(io.MultiWriter(file, hash), io.LimitReader(object, 10485761))
object.Close()
file.Close()
if copyErr != nil {
return nil, "storage_unavailable"
}
if n > 10485760 {
return nil, "invalid_image"
}
var expected string
if p.DB.QueryRow(ctx, `SELECT sha256 FROM attachments WHERE id=$1`, id).Scan(&expected) != nil {
return nil, "storage_unavailable"
}
if hex.EncodeToString(hash.Sum(nil)) != expected {
return nil, "invalid_image"
}
cmd := exec.CommandContext(ctx, "python3", "/opt/process_image.py", filepath.Join(dir, "source"), dir)
_, imagespan := telemetry.Span(ctx, "image.process", trace.SpanKindInternal)
output, err := cmd.Output()
telemetry.Result(imagespan, err)
if err != nil {
if ctx.Err() != nil {
return nil, "processing_timeout"
}
var exit *exec.ExitError
if errors.As(err, &exit) && exit.ExitCode() == 2 {
return nil, "invalid_image"
}
return nil, "processing_failed"
}
variants := []Variant{}
if json.Unmarshal(output, &variants) != nil || len(variants) != 3 {
return nil, "processing_failed"
}
var kind string
if p.DB.QueryRow(ctx, `SELECT content_type FROM attachments WHERE id=$1`, id).Scan(&kind) != nil {
return nil, "storage_unavailable"
}
source, err := os.Open(filepath.Join(dir, "source"))
if err != nil {
return nil, "storage_unavailable"
}
err = p.Objects.Put(ctx, "originals/"+id, source, n, kind)
source.Close()
if err != nil {
return nil, "storage_unavailable"
}
for _, v := range variants {
f, err := os.Open(filepath.Join(dir, v.Name))
if err != nil {
return nil, "processing_failed"
}
err = p.Objects.Put(ctx, "variants/"+id+"/v1/"+v.Name, f, v.Size, v.ContentType)
f.Close()
if err != nil {
return nil, "storage_unavailable"
}
}
return variants, ""
}
// Failed registry is PostgreSQL; explicit replay is audited and refuses successful jobs.
func (p *Pipeline) Replay(ctx context.Context, id string) error {
if uuid.Validate(id) != nil {
return fmt.Errorf("invalid job id")
}
conn, err := p.DB.Acquire(ctx)
if err != nil {
return err
}
defer conn.Release()
tx, err := conn.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var attachment, state, code string
var retained bool
err = tx.QueryRow(ctx, `SELECT attachment_id::text,state,COALESCE(error_code,''),staging_deleted_at IS NULL FROM attachment_jobs WHERE id=$1 FOR UPDATE`, id).Scan(&attachment, &state, &code, &retained)
if err != nil {
return err
}
if state != "failed" || !retained {
return fmt.Errorf("only failed jobs with retained staging can be replayed")
}
var key string
if err = tx.QueryRow(ctx, `SELECT staging_key FROM attachment_jobs WHERE id=$1`, id).Scan(&key); err != nil {
return err
}
object, err := p.Objects.Get(ctx, key)
if err != nil {
return fmt.Errorf("staging unavailable")
}
object.Close()
if _, err = tx.Exec(ctx, `INSERT INTO attachment_replays(job_id,previous_error) VALUES($1,$2)`, id, code); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state='queued',attempts=0,error_code=NULL,next_at=clock_timestamp(),lease_until=NULL,lease_token=NULL,updated_at=clock_timestamp() WHERE id=$1`, id); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, attachment); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL WHERE job_id=$1`, id); err != nil {
return err
}
return tx.Commit(ctx)
}
func (p *Pipeline) Sweep(ctx context.Context) error {
rows, err := p.DB.Query(ctx, `SELECT id::text,staging_key FROM attachment_jobs WHERE staging_deleted_at IS NULL AND (state='ready' OR (state='failed' AND updated_at<clock_timestamp()-($1*interval '1 second'))) LIMIT 20`, int64(p.Retention/time.Second))
if err != nil {
return err
}
type item struct{ id, key string }
items := []item{}
for rows.Next() {
var i item
if err = rows.Scan(&i.id, &i.key); err != nil {
rows.Close()
return err
}
items = append(items, i)
}
err = rows.Err()
rows.Close()
if err != nil {
return err
}
for _, i := range items {
tx, err := p.DB.Begin(ctx)
if err != nil {
return err
}
// Replay and retention serialize on this row. Never delete a newly queued job.
var allowed bool
err = tx.QueryRow(ctx, `SELECT state='ready' OR (state='failed' AND updated_at<clock_timestamp()-($2*interval '1 second')) FROM attachment_jobs WHERE id=$1 FOR UPDATE`, i.id, int64(p.Retention/time.Second)).Scan(&allowed)
if err != nil || !allowed {
_ = tx.Rollback(ctx)
continue
}
err = p.Objects.Delete(ctx, i.key)
if err == nil {
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET staging_deleted_at=clock_timestamp() WHERE id=$1`, i.id)
}
if err != nil {
_ = tx.Rollback(ctx)
return err
}
if err = tx.Commit(ctx); err != nil {
return err
}
}
return nil
}
// Operator commands are available only through docker exec, not through HTTP.
func (p *Pipeline) Command(ctx context.Context, args []string) error {
if len(args) == 2 && args[0] == "replay" {
return p.Replay(ctx, args[1])
}
if len(args) == 1 && args[0] == "failed-jobs" {
rows, err := p.DB.Query(ctx, `SELECT id::text,error_code,attempts FROM attachment_jobs WHERE state='failed' ORDER BY created_at`)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var id, code string
var attempts int
if err = rows.Scan(&id, &code, &attempts); err != nil {
return err
}
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{"job_id": id, "error_code": code, "attempts": attempts})
}
return rows.Err()
}
if len(args) == 3 && args[0] == "fault" && (args[1] == "arm" || args[1] == "clear") {
allowed := map[string]bool{"dispatcher_before_publish": true, "dispatcher_after_publish": true, "worker_after_claim": true, "worker_after_objects": true, "worker_before_ack": true}
if !allowed[args[2]] {
return fmt.Errorf("unknown fault point")
}
if args[1] == "clear" {
_, err := p.DB.Exec(ctx, `DELETE FROM pipeline_faults WHERE point=$1`, args[2])
return err
}
_, err := p.DB.Exec(ctx, `INSERT INTO pipeline_faults(point) VALUES($1) ON CONFLICT(point) DO UPDATE SET armed=true,hit_at=NULL`, args[2])
return err
}
return fmt.Errorf("unknown pipeline command: %s", strconv.Itoa(len(args)))
}
+22
View File
@@ -0,0 +1,22 @@
package pipeline
import (
"testing"
"time"
)
func TestRetryDelayBounds(t *testing.T) {
for attempt := 1; attempt <= 20; attempt++ {
bounded := attempt
if bounded > 6 {
bounded = 6
}
base := time.Second * time.Duration(1<<uint(bounded-1))
for i := 0; i < 100; i++ {
got := RetryDelay(attempt)
if got < base || got > base+base/2 {
t.Fatalf("attempt %d: delay %s outside [%s,%s]", attempt, got, base, base+base/2)
}
}
}
}
+102
View File
@@ -0,0 +1,102 @@
package security
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"sync/atomic"
"time"
)
var validUntil atomic.Int64
func Valid() bool { return os.Getenv("BAO_ROLE") == "" || time.Now().Unix() < validUntil.Load() }
// Certificates are locally bootstrapped, scoped, expiring identities. No root or
// permanent bootstrap token is ever mounted in an application container.
func LoadSecrets(ctx context.Context) error {
role := os.Getenv("BAO_ROLE")
if role == "" {
return nil
}
if !strings.HasPrefix(os.Getenv("BAO_ADDR"), "https://") {
return fmt.Errorf("secret authority must use HTTPS")
}
tlsConfig, e := ClientTLS()
if e != nil {
return e
}
client := &http.Client{Transport: &http.Transport{TLSClientConfig: tlsConfig}, Timeout: 3 * time.Second}
call := func(ctx context.Context, method, path, token string, body any, out any) error {
b, _ := json.Marshal(body)
req, e := http.NewRequestWithContext(ctx, method, os.Getenv("BAO_ADDR")+"/v1/"+path, bytes.NewReader(b))
if e != nil {
return e
}
req.Header.Set("Content-Type", "application/json")
if token != "" {
req.Header.Set("X-Vault-Token", token)
}
res, e := client.Do(req)
if e != nil {
return fmt.Errorf("secret authority unavailable")
}
defer res.Body.Close()
if res.StatusCode >= 300 {
return fmt.Errorf("secret authority rejected request")
}
if out != nil {
return json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(out)
}
return nil
}
refresh := func() error {
c, cancel := context.WithTimeout(context.Background(), 6*time.Second)
defer cancel()
var auth struct {
Auth struct {
Token string `json:"client_token"`
TTL int64 `json:"lease_duration"`
} `json:"auth"`
}
if e := call(c, "POST", "auth/cert/login", "", map[string]string{"name": role}, &auth); e != nil {
return e
}
var secret struct {
Data map[string]string `json:"data"`
}
if e := call(c, "GET", "secret/"+role, auth.Auth.Token, nil, &secret); e != nil {
return e
}
// Credentials are immutable during this process lifetime; rotation recreates
// only affected services, never images. Refresh validates scoped auth/lease.
if validUntil.Load() == 0 {
for k, v := range secret.Data {
if e := os.Setenv(k, v); e != nil {
return e
}
}
}
validUntil.Store(time.Now().Unix() + auth.Auth.TTL)
return nil
}
if e := refresh(); e != nil {
return e
}
go func() {
ticker := time.NewTicker(20 * time.Second)
defer ticker.Stop()
for range ticker.C {
_ = refresh()
if !Valid() && !strings.HasPrefix(role, "api") {
os.Exit(75)
}
}
}()
return nil
}
+57
View File
@@ -0,0 +1,57 @@
// Package security centralizes verified TLS and fail-closed secret leases.
package security
import (
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"strings"
)
func ClientTLS() (*tls.Config, error) {
ca, err := os.ReadFile(os.Getenv("TLS_CA_FILE"))
if err != nil {
return nil, fmt.Errorf("CA unavailable")
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(ca) {
return nil, fmt.Errorf("invalid CA")
}
c := &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots}
c.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
pair, e := tls.LoadX509KeyPair(os.Getenv("TLS_CERT_FILE"), os.Getenv("TLS_KEY_FILE"))
return &pair, e
}
return c, nil
}
func ServerTLS() (*tls.Config, error) {
c, err := ClientTLS()
if err != nil {
return nil, err
}
c.ClientCAs = c.RootCAs
c.ClientAuth = tls.RequireAndVerifyClientCert
c.GetCertificate = func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
p, e := tls.LoadX509KeyPair(os.Getenv("TLS_CERT_FILE"), os.Getenv("TLS_KEY_FILE"))
return &p, e
}
c.VerifyConnection = func(s tls.ConnectionState) error {
if len(s.PeerCertificates) == 0 {
return fmt.Errorf("client identity missing")
}
cert := s.PeerCertificates[0]
for _, san := range cert.DNSNames {
if san == "lb" || san == os.Getenv("TLS_SERVER_NAME") {
revoked, _ := os.ReadFile("/run/ca/revoked-serials")
if strings.Contains("\n"+string(revoked)+"\n", "\n"+cert.SerialNumber.Text(16)+"\n") {
return fmt.Errorf("revoked identity")
}
return nil
}
}
return fmt.Errorf("client identity denied")
}
return c, nil
}
+74
View File
@@ -0,0 +1,74 @@
package telemetry
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"net"
"strings"
)
// Queries are named by operation only. SQL text/args never enter telemetry.
type DBTracer struct{}
func (DBTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context {
if !trace.SpanContextFromContext(ctx).IsValid() {
return ctx
}
op := "OTHER"
f := strings.Fields(d.SQL)
if len(f) > 0 {
switch strings.ToUpper(f[0]) {
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK", "CREATE", "ALTER":
op = strings.ToUpper(f[0])
}
}
c, _ := Span(ctx, "db."+strings.ToLower(op), trace.SpanKindClient, attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", op))
return c
}
func (DBTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryEndData) {
if trace.SpanContextFromContext(ctx).IsValid() {
Result(trace.SpanFromContext(ctx), d.Err)
}
}
func (DBTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
Waiting.Add(1)
if trace.SpanContextFromContext(ctx).IsValid() {
c, _ := Span(ctx, "db.pool.acquire", trace.SpanKindClient, attribute.String("db.system.name", "postgresql"))
return c
}
return ctx
}
func (DBTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) {
Waiting.Add(-1)
if trace.SpanContextFromContext(ctx).IsValid() {
Result(trace.SpanFromContext(ctx), data.Err)
}
}
type RedisHook struct{}
func (RedisHook) DialHook(next redis.DialHook) redis.DialHook {
return func(ctx context.Context, network, addr string) (net.Conn, error) { return next(ctx, network, addr) }
}
func (RedisHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
return func(ctx context.Context, cmd redis.Cmder) error {
if !trace.SpanContextFromContext(ctx).IsValid() {
return next(ctx, cmd)
}
c, s := Span(ctx, "redis."+cmd.Name(), trace.SpanKindClient, attribute.String("db.system.name", "redis"), attribute.String("db.operation.name", cmd.Name()))
err := next(c, cmd)
if err == redis.Nil {
s.End()
} else {
Result(s, err)
}
return err
}
}
func (RedisHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
return next
}
+93
View File
@@ -0,0 +1,93 @@
package telemetry
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"os"
"runtime"
"strconv"
"strings"
"syscall"
"time"
)
func Monitor(pool *pgxpool.Pool, role string, capacity int) error {
m := otel.Meter(Scope)
names := []string{"messenger_db_pool_used", "messenger_db_pool_idle", "messenger_db_pool_waiting", "messenger_db_pool_capacity", "messenger_worker_busy", "messenger_worker_capacity", "messenger_queue_depth", "messenger_queue_oldest_age_seconds", "messenger_db_available", "messenger_process_memory_bytes", "messenger_container_memory_bytes", "messenger_container_memory_limit_bytes", "messenger_telemetry_export_errors", "messenger_process_last_observed_seconds"}
gauges := map[string]metric.Int64ObservableGauge{}
for _, n := range names {
g, err := m.Int64ObservableGauge(n)
if err != nil {
return err
}
gauges[n] = g
}
containerCPU, _ := m.Float64ObservableCounter("messenger_container_cpu", metric.WithUnit("s"))
cpu, _ := m.Float64ObservableCounter("messenger_process_cpu", metric.WithUnit("s"))
acquired, _ := m.Int64ObservableCounter("messenger_db_pool_acquire_wait")
duration, _ := m.Float64ObservableCounter("messenger_db_pool_acquire_wait_duration", metric.WithUnit("s"))
instruments := []metric.Observable{cpu, containerCPU, acquired, duration}
for _, g := range gauges {
instruments = append(instruments, g)
}
_, err := m.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
stat := pool.Stat()
observeTime := time.Now().Unix()
observe := func(n string, value int64) { o.ObserveInt64(gauges[n], value) }
observe("messenger_db_pool_used", int64(stat.AcquiredConns()))
observe("messenger_db_pool_idle", int64(stat.IdleConns()))
observe("messenger_db_pool_waiting", Waiting.Load())
observe("messenger_db_pool_capacity", int64(stat.MaxConns()))
o.ObserveInt64(acquired, stat.EmptyAcquireCount())
o.ObserveFloat64(duration, stat.EmptyAcquireWaitTime().Seconds())
observe("messenger_telemetry_export_errors", ExportErrors.Load())
observe("messenger_process_last_observed_seconds", observeTime)
if role == "worker" {
observe("messenger_worker_busy", Busy.Load())
observe("messenger_worker_capacity", int64(capacity))
}
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
observe("messenger_process_memory_bytes", int64(mem.Sys))
for file, name := range map[string]string{"memory.current": "messenger_container_memory_bytes", "memory.max": "messenger_container_memory_limit_bytes"} {
if b, e := os.ReadFile("/sys/fs/cgroup/" + file); e == nil {
if n, e := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64); e == nil {
observe(name, n)
}
}
}
if raw, e := os.ReadFile("/sys/fs/cgroup/cpu.stat"); e == nil {
for _, line := range strings.Split(string(raw), "\n") {
fields := strings.Fields(line)
if len(fields) == 2 && fields[0] == "usage_usec" {
if n, e := strconv.ParseFloat(fields[1], 64); e == nil {
o.ObserveFloat64(containerCPU, n/1e6)
}
}
}
}
var usage syscall.Rusage
if syscall.Getrusage(syscall.RUSAGE_SELF, &usage) == nil {
o.ObserveFloat64(cpu, float64(usage.Utime.Sec+usage.Stime.Sec)+float64(usage.Utime.Usec+usage.Stime.Usec)/1e6)
}
if role == "dispatcher" {
c, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
var depth, age int64
e := pool.QueryRow(c, `SELECT count(*),COALESCE(EXTRACT(EPOCH FROM clock_timestamp()-min(created_at))::bigint,0) FROM attachment_jobs WHERE state='queued'`).Scan(&depth, &age)
if e == nil {
o.ObserveInt64(gauges["messenger_queue_depth"], depth, metric.WithAttributes(attribute.String("queue", "attachment.jobs.v1")))
o.ObserveInt64(gauges["messenger_queue_oldest_age_seconds"], age, metric.WithAttributes(attribute.String("queue", "attachment.jobs.v1")))
observe("messenger_db_available", 1)
} else {
observe("messenger_db_available", 0)
}
}
return nil
}, instruments...)
return err
}
+213
View File
@@ -0,0 +1,213 @@
// Package telemetry exports bounded, asynchronous OTLP signals without business payloads.
package telemetry
import (
"context"
"encoding/json"
"fmt"
"mtusi-messenger/internal/security"
"os"
"strings"
"sync/atomic"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
otellog "go.opentelemetry.io/otel/log"
logglobal "go.opentelemetry.io/otel/log/global"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
sdklog "go.opentelemetry.io/otel/sdk/log"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
)
const Scope = "mtusi-messenger/telemetry-v1"
var Service = "messenger-api"
var Busy atomic.Int64
var Waiting atomic.Int64
var ExportErrors atomic.Int64
var signals *Signals
type Signals struct {
Requests metric.Int64Counter
HTTPDuration metric.Float64Histogram
Jobs metric.Int64Counter
JobDuration metric.Float64Histogram
ReadyDuration metric.Float64Histogram
}
func Start(ctx context.Context, service, instance string) (func(context.Context) error, error) {
if !strings.HasPrefix(os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT"), "https://") {
return nil, fmt.Errorf("OTLP requires HTTPS")
}
Service = service
tc, e := security.ClientTLS()
if e != nil {
return nil, e
}
otel.SetTextMapPropagator(propagation.TraceContext{})
attrs := []attribute.KeyValue{attribute.String("service.name", service), attribute.String("service.version", "lab6-v1"), attribute.String("service.instance.id", instance), attribute.String("deployment.environment.name", "lab")}
res := resource.NewWithAttributes("https://opentelemetry.io/schemas/1.37.0", attrs...)
traceExp, err := otlptracehttp.New(ctx, otlptracehttp.WithTLSClientConfig(tc), otlptracehttp.WithTimeout(2*time.Second), otlptracehttp.WithRetry(otlptracehttp.RetryConfig{Enabled: false}))
if err != nil {
return nil, err
}
metricExp, err := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTLSClientConfig(tc), otlpmetrichttp.WithTimeout(2*time.Second), otlpmetrichttp.WithRetry(otlpmetrichttp.RetryConfig{Enabled: false}))
if err != nil {
return nil, err
}
logExp, err := otlploghttp.New(ctx, otlploghttp.WithTLSClientConfig(tc), otlploghttp.WithTimeout(2*time.Second), otlploghttp.WithRetry(otlploghttp.RetryConfig{Enabled: false}))
if err != nil {
return nil, err
}
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), sdktrace.WithBatcher(traceExp, sdktrace.WithMaxQueueSize(256), sdktrace.WithMaxExportBatchSize(64), sdktrace.WithBatchTimeout(500*time.Millisecond), sdktrace.WithExportTimeout(2*time.Second)))
mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res), sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExp, sdkmetric.WithInterval(2*time.Second), sdkmetric.WithTimeout(2*time.Second))))
lp := sdklog.NewLoggerProvider(sdklog.WithResource(res), sdklog.WithProcessor(sdklog.NewBatchProcessor(logExp, sdklog.WithMaxQueueSize(256), sdklog.WithExportMaxBatchSize(64), sdklog.WithExportInterval(500*time.Millisecond), sdklog.WithExportTimeout(2*time.Second))))
otel.SetTracerProvider(tp)
otel.SetMeterProvider(mp)
logglobal.SetLoggerProvider(lp)
// No exporter/network details, payloads or credentials are logged on errors.
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(error) { ExportErrors.Add(1) }))
meter := otel.Meter(Scope)
s := &Signals{}
s.Requests, err = meter.Int64Counter("messenger_http_requests")
if err != nil {
return nil, err
}
buckets := []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 30, 60, 120}
s.HTTPDuration, _ = meter.Float64Histogram("messenger_http_duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(buckets...))
s.Jobs, _ = meter.Int64Counter("messenger_jobs_processed")
s.JobDuration, _ = meter.Float64Histogram("messenger_job_duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(buckets...))
s.ReadyDuration, _ = meter.Float64Histogram("messenger_time_to_ready", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.1, .5, 1, 5, 10, 30, 60, 120, 300, 900, 3600, 86400))
signals = s
return func(c context.Context) error {
// Shared deadline bounds shutdown across all signals.
a := tp.Shutdown(c)
b := mp.Shutdown(c)
d := lp.Shutdown(c)
if a != nil || b != nil || d != nil {
return fmt.Errorf("telemetry shutdown incomplete")
}
return nil
}, nil
}
func Span(ctx context.Context, name string, kind trace.SpanKind, attrs ...attribute.KeyValue) (context.Context, trace.Span) {
return otel.Tracer(Scope).Start(ctx, name, trace.WithSpanKind(kind), trace.WithAttributes(attrs...))
}
func Result(span trace.Span, err error) {
if err != nil {
span.SetStatus(codes.Error, "dependency unavailable")
span.SetAttributes(attribute.Bool("error", true))
}
span.End()
}
func Inject(ctx context.Context) (string, string) {
c := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, c)
return c.Get("traceparent"), c.Get("tracestate")
}
func Extract(ctx context.Context, parent, state string) context.Context {
return otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state})
}
type requestKey struct{}
func WithRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, requestKey{}, id)
}
func RequestID(ctx context.Context) string { v, _ := ctx.Value(requestKey{}).(string); return v }
func Event(ctx context.Context, event string, fields map[string]any) {
sc := trace.SpanContextFromContext(ctx)
body := map[string]any{"timestamp": time.Now().UTC().Format(time.RFC3339Nano), "severity": "INFO", "service.name": Service, "event": event}
if sc.IsValid() {
body["trace_id"] = sc.TraceID().String()
body["span_id"] = sc.SpanID().String()
}
if id, ok := ctx.Value(requestKey{}).(string); ok {
body["request_id"] = id
}
for k, v := range fields {
body[k] = v
}
severity := otellog.SeverityInfo
if status, ok := fields["status"].(int); ok && status >= 500 {
severity = otellog.SeverityError
}
if outcome, ok := fields["outcome"].(string); ok && (outcome == "failed" || outcome == "retry" || outcome == "abandoned") {
severity = otellog.SeverityError
}
if severity == otellog.SeverityError {
body["severity"] = "ERROR"
}
encoded, _ := json.Marshal(body)
_, _ = os.Stdout.Write(append(encoded, '\n'))
var record otellog.Record
record.SetTimestamp(time.Now())
record.SetSeverity(severity)
record.SetSeverityText(body["severity"].(string))
record.SetBody(attribute.StringValue(string(encoded)))
record.AddAttributes(attribute.String("event", event))
logglobal.GetLoggerProvider().Logger(Scope).Emit(ctx, record)
}
func HTTP(ctx context.Context, method, route string, status int, elapsed time.Duration) {
if signals == nil {
return
}
a := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", fmt.Sprintf("%dxx", status/100)))
signals.Requests.Add(ctx, 1, a)
signals.HTTPDuration.Record(ctx, elapsed.Seconds(), a)
}
func Job(ctx context.Context, outcome string, d time.Duration) {
if signals == nil {
return
}
a := metric.WithAttributes(attribute.String("job_type", "attachment.process.v1"), attribute.String("outcome", outcome))
signals.Jobs.Add(ctx, 1, a)
signals.JobDuration.Record(ctx, d.Seconds(), a)
}
func Ready(ctx context.Context, d time.Duration) {
if signals != nil {
signals.ReadyDuration.Record(ctx, d.Seconds(), metric.WithAttributes(attribute.String("job_type", "attachment.process.v1")))
}
}
func Method(s string) string {
switch s {
case "GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS":
return s
}
return "OTHER"
}
func Route(path string) string {
switch path {
case "/health/live", "/health/ready", "/api/v1/users", "/api/v1/users/me", "/api/v1/auth/sessions", "/api/v1/auth/sessions/current", "/api/v1/chats":
return path
}
parts := strings.Split(strings.Trim(path, "/"), "/")
if len(parts) >= 4 && parts[0] == "api" && parts[1] == "v1" {
if parts[2] == "chats" {
if len(parts) == 4 {
return "/api/v1/chats/{chat_id}"
}
if len(parts) == 5 && (parts[4] == "messages" || parts[4] == "attachments") {
return "/api/v1/chats/{chat_id}/" + parts[4]
}
}
if parts[2] == "attachments" {
if len(parts) == 4 {
return "/api/v1/attachments/{attachment_id}"
}
if len(parts) == 5 && parts[4] == "content" {
return "/api/v1/attachments/{attachment_id}/content"
}
}
}
return "/unmatched"
}
+28
View File
@@ -0,0 +1,28 @@
package telemetry
import (
"strings"
"testing"
)
func TestRouteLabelsNeverContainResourceIDs(t *testing.T) {
ids := []string{"11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222"}
for _, id := range ids {
cases := map[string]string{
"/api/v1/chats/" + id: "/api/v1/chats/{chat_id}",
"/api/v1/chats/" + id + "/messages": "/api/v1/chats/{chat_id}/messages",
"/api/v1/chats/" + id + "/attachments": "/api/v1/chats/{chat_id}/attachments",
"/api/v1/attachments/" + id + "/content": "/api/v1/attachments/{attachment_id}/content",
"/arbitrary/" + id: "/unmatched",
}
for input, want := range cases {
got := Route(input)
if got != want || strings.Contains(got, id) {
t.Fatalf("unsafe route label %q for %q", got, input)
}
}
}
if Method("CUSTOM-USER-METHOD") != "OTHER" {
t.Fatal("unbounded method label")
}
}
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Explicit operator init/unseal/configure. Operator material never mounted in apps."""
import json,os,ssl,sys,urllib.request,urllib.error
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];os.chdir(ROOT);os.umask(0o077)
BASE=Path('secrets');local=dict(line.split('=',1) for line in Path('.env').read_text().splitlines() if '=' in line and not line.startswith('#'))
ADDR=os.environ.get('BAO_OPERATOR_ADDR','https://localhost:'+os.environ.get('BAO_PORT',local.get('BAO_PORT','18200')))
ctx=ssl.create_default_context(cafile=str(BASE/'public/ca.crt'))
def call(method,path,data=None,token=None):
req=urllib.request.Request(ADDR+'/v1/'+path,data=None if data is None else json.dumps(data).encode(),method=method,headers={'Content-Type':'application/json',**({'X-Vault-Token':token} if token else {})})
with urllib.request.urlopen(req,context=ctx,timeout=10) as r:return json.load(r) if r.status!=204 else {}
def main():
mode=sys.argv[1] if len(sys.argv)>1 else ''
if mode not in ('init','unseal','configure','seal','wait'):raise SystemExit('usage: bao-operator.py init|unseal|configure|seal')
if mode=='wait':
import time
for _ in range(60):
try:call('GET','sys/init');return
except OSError:time.sleep(.5)
raise SystemExit('OpenBao listener unavailable')
f=BASE/'operator/bao-init.json'
if mode=='init' and not f.exists():
if call('GET','sys/init')['initialized']:raise SystemExit('Already initialized: restore operator init file, never reinitialize persistent storage.')
f.write_text(json.dumps(call('PUT','sys/init',{'secret_shares':1,'secret_threshold':1})))
state=json.loads(f.read_text());token=state['root_token']
if mode=='seal':call('PUT','sys/seal',{},token);print('OpenBao sealed.');return
if mode in ('init','unseal'):
call('PUT','sys/unseal',{'key':state['keys'][0]})
if mode in ('init','configure'):
mounts=call('GET','sys/mounts',token=token)
if 'secret/' not in mounts:call('POST','sys/mounts/secret',{'type':'kv','options':{'version':'1'}},token)
auth=call('GET','sys/auth',token=token)
if 'cert/' not in auth:call('POST','sys/auth/cert',{'type':'cert'},token)
for role,values in json.loads((BASE/'operator/service-secrets.json').read_text()).items():
policy=(ROOT/'infra/security/policies'/f'{role}.hcl').read_text()
call('PUT','sys/policies/acl/'+role,{'policy':policy},token)
# Bind exact leaf, not whole CA: rotation can revoke old auth by replacing cert.
cert=(BASE/'tls'/role/'cert.crt').read_text()
call('POST','auth/cert/certs/'+role,{'certificate':cert,'allowed_dns_sans':[role],'token_policies':[role],'token_ttl':60,'token_max_ttl':120,'token_no_default_policy':True},token)
call('POST','secret/'+role,values,token)
print('OpenBao operator action complete; no secret values displayed.')
if __name__=='__main__':
try:main()
except (urllib.error.URLError,KeyError,OSError) as e:raise SystemExit('Operator action failed; check OpenBao readiness and local operator files.') from None
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
python3 scripts/pki.py
python3 scripts/prepare-secrets.py
printf '%s\n' 'Local material ready. Start openbao, then explicitly run scripts/bao-operator.py init (or unseal after Bao restart).'
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Operator-only PKI bootstrap. Never prints keys or secret values."""
import argparse, os, subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
BASE=ROOT/'secrets'
def run(*args): subprocess.run(args,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE)
def issue(name,renew=False):
d=BASE/'tls'/name;d.mkdir(parents=True,exist_ok=True)
if (d/'cert.crt').exists() and not renew:return
ext=d/'extensions.cnf'
sans=[name]
if name in ('api1','api2'):sans+=['messenger-api']
if name in ('lb','grafana','openbao'):sans+=['localhost']
ext.write_text('basicConstraints=critical,CA:FALSE\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName='+','.join('DNS:'+s for s in sans)+',IP:127.0.0.1\n')
run('openssl','req','-new','-newkey','rsa:2048','-nodes','-subj','/CN='+name,'-keyout',str(d/'key.new'),'-out',str(d/'request.csr'))
run('openssl','x509','-req','-in',str(d/'request.csr'),'-CA',str(BASE/'public/ca.crt'),'-CAkey',str(BASE/'operator/ca.key'),'-set_serial',str(int.from_bytes(os.urandom(16),'big')),'-days','7','-sha256','-extfile',str(ext),'-out',str(d/'cert.new'))
for src,dst in [('key.new','key.key'),('cert.new','cert.crt')]:
os.chmod(d/src,0o444);os.replace(d/src,d/dst)
for f in ['request.csr','extensions.cnf']: (d/f).unlink()
def main():
p=argparse.ArgumentParser();p.add_argument('--rotate');a=p.parse_args()
os.umask(0o077)
for x in ['operator','public','tls']: (BASE/x).mkdir(parents=True,exist_ok=True)
if not (BASE/'operator/ca.key').exists():
run('openssl','req','-x509','-newkey','rsa:3072','-nodes','-days','365','-sha256','-subj','/CN=MTUSI Lab7 local CA','-keyout',str(BASE/'operator/ca.key'),'-out',str(BASE/'public/ca.crt'),'-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign','-addext','subjectKeyIdentifier=hash')
os.chmod(BASE/'public/ca.crt',0o444)
if not (BASE/'public/revoked-serials').exists(): (BASE/'public/revoked-serials').write_text('')
os.chmod(BASE/'public/revoked-serials',0o444)
roles=['lb','api1','api2','worker','dispatcher','cleanup','migrate','s3-init','postgres','redis','broker','s3','otel-collector','prometheus','loki','tempo','grafana','openbao','operator','outsider']
for role in roles:issue(role,a.rotate in (role,"all"))
if a.rotate and a.rotate not in roles+["all"]:raise SystemExit('unknown identity')
foreign=BASE/'tls/foreign';foreign.mkdir(exist_ok=True);foreign.chmod(0o755)
if not (foreign/'cert.crt').exists():
run('openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','7','-subj','/CN=untrusted','-keyout',str(foreign/'key.key'),'-out',str(foreign/'cert.crt'))
for f in foreign.iterdir():f.chmod(0o444)
print('PKI ready; private CA remains operator-only.')
if __name__=='__main__':main()
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
import json,os,secrets
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];os.chdir(ROOT);os.umask(0o077)
base=Path('secrets');base.mkdir(exist_ok=True);base.chmod(0o700)
def value(name):
p=base/name
if not p.exists():p.write_text(secrets.token_hex(24))
return p.read_text().strip()
pg=value('postgres_password');rp=value('redis_password');bp=value('broker_password')
for k in ['s3_admin_access','s3_admin_secret','grafana_admin_password']:value(k)
if (base/'database_url').exists():(base/'database_url').chmod(0o600)
(base/'database_url').write_text(f'postgres://messenger:{pg}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/ca/ca.crt')
path=base/'operator/service-secrets.json'
if not path.exists():
data={}
for role in ['api1','api2','worker','dispatcher','cleanup','migrate']:
user='api' if role.startswith('api') else role
pwd=pg if role=='migrate' else value('db_'+user)
access=value('s3_'+user+'_access');secret=value('s3_'+user+'_secret')
data[role]={'DATABASE_URL':f'postgres://{("messenger" if role=="migrate" else user)}:{pwd}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/ca/ca.crt', 'S3_ACCESS_KEY_ID':access,'S3_SECRET_ACCESS_KEY':secret}
if role.startswith('api'):data[role]['CACHE_URL']=f'rediss://:{rp}@redis:6379/0'
if role in ['dispatcher','worker']:data[role]['BROKER_URL']=f'rediss://:{bp}@broker:6379/0'
path.write_text(json.dumps(data))
data=json.loads(path.read_text())
# Separate producer/consumer credentials and command ACLs for the broker.
lines=['user default off']
for role,commands in [('dispatcher','+xadd'),('worker','+xgroup +xautoclaim +xreadgroup +xack +xdel (+xadd ~attachment.invalid.dlq)'),('operator','+@all')]:
pwd=value('broker_'+role)
lines.append(f'user {role} on >{pwd} ~attachment.* {commands} +ping +hello +client|setinfo')
if role in data:data[role]['BROKER_URL']=f'rediss://{role}:{pwd}@broker:6379/0'
if (base/'broker.acl').exists():(base/'broker.acl').chmod(0o600)
(base/'broker.acl').write_text('\n'.join(lines)+'\n');(base/'broker.acl').chmod(0o444)
path.chmod(0o600)
path.write_text(json.dumps(data))
# Sessions have a separate limited user; API cannot CONFIG/FLUSHALL or read other prefixes.
radmin=value('redis_operator')
redis_acl=base/'redis.acl'
if redis_acl.exists():redis_acl.chmod(0o600)
redis_acl.write_text('user default off\n'+f'user api on >{rp} ~session:* ~login:* +get +set +del +ping +hello +client|setinfo +eval +incr +expire\n'+f'user operator on >{radmin} ~* +@all\n')
redis_acl.chmod(0o444)
for role in ['api1','api2']:data[role]['CACHE_URL']=f'rediss://api:{rp}@redis:6379/0'
path.chmod(0o600);path.write_text(json.dumps(data))
# No root token, CA private key or unseal key mounted into database setup.
statements=[]
for role in ['api','worker','dispatcher','cleanup']:
pwd=value('db_'+role)
statements.append(f"DO $role$ BEGIN IF NOT EXISTS(SELECT 1 FROM pg_roles WHERE rolname='{role}') THEN CREATE ROLE {role} LOGIN PASSWORD '{pwd}'; END IF; END $role$;")
statements.append(f'GRANT CONNECT ON DATABASE messenger TO {role}; GRANT USAGE ON SCHEMA public TO {role};')
statements+=['GRANT SELECT,INSERT,UPDATE,DELETE ON users,chats,chat_members,messages,message_idempotency,attachments,attachment_uploads,attachment_jobs,attachment_outbox TO api;', 'GRANT SELECT,UPDATE ON attachments,attachment_jobs TO worker;', 'GRANT SELECT,UPDATE ON attachment_jobs,attachment_outbox,attachments TO dispatcher;', 'GRANT SELECT ON attachments,attachment_jobs TO cleanup; GRANT SELECT,DELETE ON attachment_uploads TO cleanup;', 'GRANT SELECT,UPDATE ON pipeline_faults TO worker,dispatcher;', 'GRANT SELECT,INSERT ON attachment_replays TO dispatcher; GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO dispatcher;']
if (base/'db-grants.sql').exists():(base/'db-grants.sql').chmod(0o600)
(base/'db-grants.sql').write_text('\n'.join(statements))
if not Path('.env').exists():Path('.env').write_text('APP_PORT=8443\nGRAFANA_PORT=13007\nBAO_PORT=18200\nSESSION_TTL_SECONDS=3600\nWORKER_CONCURRENCY=1\n')
env=Path('.env')
text=env.read_text()
for k,v in [('LOCAL_UID',os.getuid()),('LOCAL_GID',os.getgid())]:
if k+'=' not in text:text+=f'{k}={v}\n'
env.write_text(text)
for d in (base/'tls').iterdir():
if d.is_dir():d.chmod(0o755)
(base/'public').chmod(0o755)
# Parent secrets/ remains0700; only individually mounted runtime files are readable
# by non-root container UIDs on Linux. Operator root/unseal/CA key remain0600.
for name in ['postgres_password','redis_password','redis_operator','broker_operator','grafana_admin_password','database_url','s3_admin_access','s3_admin_secret','db-grants.sql']:
(base/name).chmod(0o444)
path.chmod(0o444)
print('Generated local credentials; values suppressed.')
+22
View File
@@ -0,0 +1,22 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose --env-file .env restart openbao >/dev/null
# This is an explicit operator hook, not auto-unseal inside a server container.
python3 scripts/bao-operator.py wait
python3 scripts/bao-operator.py unseal
docker compose --env-file .env restart postgres redis s3 broker >/dev/null
docker compose --env-file .env restart api1 api2 cleanup dispatcher worker >/dev/null
docker compose --env-file .env restart otel-collector prometheus loki tempo grafana nginx >/dev/null
python3 - <<'PY'
import ssl,time,urllib.request
from pathlib import Path
c=ssl.create_default_context(cafile='secrets/public/ca.crt')
for i in range(120):
try:
with urllib.request.urlopen('https://localhost:8443/health/ready',context=c,timeout=2) as r:
if r.status==200:break
except OSError:pass
time.sleep(.5)
else:raise SystemExit('stack did not recover')
PY
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Operator rotates worker DB password; old authentication is invalidated.
The secret travels to psql only through stdin, never argv/logs/evidence.
"""
import json,os,secrets,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];os.chdir(ROOT);os.umask(0o077)
p=Path('secrets/operator/service-secrets.json');data=json.loads(p.read_text());pwd=secrets.token_hex(24)
from urllib.parse import urlsplit,urlunsplit
u=urlsplit(data['worker']['DATABASE_URL']);data['worker']['DATABASE_URL']=urlunsplit((u.scheme,'worker:'+pwd+'@'+u.hostname+':5432',u.path,u.query,u.fragment))
result=subprocess.run(['docker','compose','--env-file','.env','exec','-T','postgres','psql','-Xq','-v','ON_ERROR_STOP=1','-U','messenger','-d','messenger'],input="ALTER ROLE worker PASSWORD '"+pwd+"';\n",text=True,capture_output=True)
if result.returncode:raise SystemExit('database password rotation failed')
p.chmod(0o600);p.write_text(json.dumps(data));p.chmod(0o444);Path('secrets/db_worker').write_text(pwd)
subprocess.run(['python3','scripts/bao-operator.py','configure'],check=True)
subprocess.run(['docker','compose','--env-file','.env','restart','worker'],check=True,stdout=subprocess.DEVNULL)
print('Worker DB secret rotated, active worker recreated its pool; images unchanged.')
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
"""Operator rollover: issue leaf, revoke old serial, replace Bao binding, restart
only the affected service (and LB reload), with no image build. Old key retained
operator-side solely for the explicit negative verification, never mounted in app.
"""
import os,shutil,subprocess,sys
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];os.chdir(ROOT)
role=sys.argv[1] if len(sys.argv)>1 else ''
if role not in ['lb','api1','api2','worker','dispatcher','cleanup']:raise SystemExit('choose lb/api1/api2/worker/dispatcher/cleanup')
def command(*args):subprocess.run(args,check=True,stdout=subprocess.DEVNULL)
d=Path('secrets/tls')/role;old=Path('secrets/operator/previous-leaf')/role;old.mkdir(parents=True,exist_ok=True)
for name in ['cert.crt','key.key']:
if (old/name).exists():(old/name).chmod(0o600)
shutil.copy2(d/name,old/name)
serial=subprocess.check_output(['openssl','x509','-in',str(old/'cert.crt'),'-serial','-noout'],text=True).strip().split('=')[1].lower().lstrip('0')
command('python3','scripts/pki.py','--rotate',role)
p=Path('secrets/public/revoked-serials');p.chmod(0o600)
with p.open('a') as f:f.write(serial+'\n')
p.chmod(0o444)
if role!='lb':command('python3','scripts/bao-operator.py','configure')
service='nginx' if role=='lb' else role
command('docker','compose','--env-file','.env','restart',service)
print('Leaf rotated; old serial denied on new connections; images unchanged.')
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Operator-only dependency/image scan, no Docker socket mounted in scanner.
Raw outputs stay in a temporary directory; Git gets a compact, non-secret summary.
"""
import collections,json,os,subprocess,tempfile
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];os.chdir(ROOT)
def run(args,**kw):return subprocess.run(args,check=True,**kw)
def read_stream(text):
out=[];decoder=json.JSONDecoder()
while text.strip():
value,n=decoder.raw_decode(text.lstrip());out.append(value);text=text.lstrip()[n:]
return out
def summarize(scan):
return [{'target':r['Target'],'severity_counts':dict(collections.Counter(v['Severity'] for v in r.get('Vulnerabilities',[]))),
'findings':[{'id':v['VulnerabilityID'],'package':v['PkgName'],'installed':v['InstalledVersion'],'fixed':v.get('FixedVersion'),'severity':v['Severity']} for v in r.get('Vulnerabilities',[]) if v['Severity'] in ('HIGH','CRITICAL')]}for r in scan.get('Results',[])]
def main():
summary={'date':'2026-11-23','scanner':'aquasec/trivy:0.76.2','images':{}}
with tempfile.TemporaryDirectory(prefix='lab7-scan-') as tmp:
path=Path(tmp)
for name in ['api','worker']:
image=f'mtusi-lab7-{name}:local';archive=path/(name+'.tar');report=path/(name+'.json')
run(['docker','save','-o',str(archive),image])
run(['docker','run','--rm','--cpus','1','--memory','768m','-v',tmp+':/scan','-v','mtusi-lab7-trivy-cache:/root/.cache/','aquasec/trivy:0.76.2','image','--input','/scan/'+archive.name,'--scanners','vuln','--format','json','--output','/scan/'+report.name])
scanned=json.loads(report.read_text());summary['images'][image]={'metadata':scanned.get('Metadata',{}),'results':summarize(scanned)}
env=dict(os.environ,GOTOOLCHAIN='go1.26.11',CGO_ENABLED='0')
p=subprocess.run(['go','run','golang.org/x/vuln/cmd/govulncheck@v1.1.4','-json','./...'],env=env,capture_output=True,text=True)
if p.returncode not in (0,3):raise SystemExit('govulncheck failed')
findings=[d['finding']for d in read_stream(p.stdout)if 'finding'in d]
summary['go']={'tool':'govulncheck v1.1.4','toolchain':'go1.26.11','ids':sorted({d['osv']for d in findings}),'function_locations':sorted({d['trace'][0].get('package','')+'.'+d['trace'][0].get('function','')for d in findings if d.get('trace',[{}])[0].get('function')})}
(ROOT/'evidence/scan-summary.json').write_text(json.dumps(summary,indent=2)+'\n')
print('Scan complete; assess applicability using infra/security/scan-triage.md, not severity counts alone.')
if __name__=='__main__':main()
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose --env-file .env start api1 api2 >/dev/null
for service in api1 api2; do
container_id=$(docker compose --env-file .env ps -q "$service")
attempts=0
until [ "$(docker inspect --format '{{.State.Health.Status}}' "$container_id" 2>/dev/null || true)" = healthy ]; do
attempts=$((attempts + 1))
if [ "$attempts" -ge 60 ]; then
printf '%s\n' "$service did not become healthy" >&2
exit 1
fi
sleep 1
done
done
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
sh scripts/init-local.sh
docker compose --env-file .env up -d openbao
python3 scripts/bao-operator.py wait
# Explicit operator action. The server does not receive unseal material.
python3 scripts/bao-operator.py init
docker compose --env-file .env up -d --build --wait
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
api-1) service=api1 ;;
api-2) service=api2 ;;
*) printf '%s\n' "Unknown API instance alias" >&2; exit 2 ;;
esac
docker compose --env-file .env stop --timeout 3 "$service" >/dev/null
+66
View File
@@ -0,0 +1,66 @@
"""Read stored signals through internal backend APIs; no public admin ports."""
import json
import time
import urllib.parse
import urllib.request
import urllib.error
import base64
import ssl
from pipeline_helpers import *
def backend(url, text=False):
# Query via Grafana proxy: observation must work even while worker is stopped.
target=urllib.parse.urlsplit(url)
sources={'prometheus:9090':'prometheus','loki:3100':'loki','tempo:3200':'tempo'}
check(target.netloc in sources,'unknown telemetry backend')
password=(ROOT/'secrets/grafana_admin_password').read_text().strip()
base=os.environ.get('GRAFANA_URL','https://localhost:13007').rstrip('/')
address=base+'/api/datasources/proxy/uid/'+sources[target.netloc]+target.path
if target.query:address+='?'+target.query
auth=base64.b64encode(('admin:'+password).encode()).decode()
request=urllib.request.Request(address,headers={'Accept':'application/json','Authorization':'Basic '+auth})
try:
with urllib.request.urlopen(request,timeout=8,context=ssl.create_default_context(cafile=str(ROOT/"secrets/public/ca.crt"))) as response:output=response.read().decode()
return output if text else json.loads(output)
except (urllib.error.URLError,OSError,ValueError):
raise Failure('telemetry backend not ready: '+sources[target.netloc]) from None
def prom(expr):
result=backend('https://prometheus:9090/api/v1/query?'+urllib.parse.urlencode({'query':expr}))
check(result['status']=='success','Prometheus query failed')
return result['data']['result']
def number(expr, default=0):
values=prom(expr)
return float(values[0]['value'][1]) if values else default
def trace_data(trace_id):
return backend('https://tempo:3200/api/traces/'+trace_id)
def spans(value):
found=[]
if isinstance(value,dict):
if 'spanId' in value and 'name' in value:found.append(value)
for child in value.values():found.extend(spans(child))
elif isinstance(value,list):
for child in value:found.extend(spans(child))
return found
def logs(trace_id=None, service=None):
selector='{service_name="'+service+'"}' if service else '{service_name=~"messenger-api|messenger-worker|messenger-dispatcher"}'
query=selector+' | json'
if trace_id:query+=' | trace_id="'+trace_id+'"'
data=backend('https://loki:3100/loki/api/v1/query_range?'+urllib.parse.urlencode({'query':query,'start':str(time.time_ns()-900_000_000_000),'limit':'1000'}))
return [json.loads(row[1]) for stream in data['data']['result'] for row in stream['values']]
def alert(name):
result=backend('https://prometheus:9090/api/v1/alerts')
matches=[a for a in result['data']['alerts'] if a['labels'].get('alertname')==name]
return matches[0]['state'] if matches else 'resolved'
+83
View File
@@ -0,0 +1,83 @@
"""Local synthetic tests; credentials stay in memory and never enter evidence."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check, run
def compose(*args, data=None):
result = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
input=data, capture_output=True, text=True)
check(result.returncode == 0, 'compose command failed: ' + ' '.join(args[:3]))
return result.stdout.strip()
def psql(sql):
return compose('exec', '-T', 'postgres', 'psql', '-XAtq', '-v', 'ON_ERROR_STOP=1',
'-U', 'messenger', '-d', 'messenger', data=sql)
def wait_for(test, message, timeout=100):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
value = test()
if value:
return value
except Failure:
pass
time.sleep(.3)
raise Failure(message)
def ready(client):
wait_for(lambda: client.call('GET', '/health/ready', schema='Health'), 'API not ready')
def upload(client, actor, chat, raw=None):
if raw is None:
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
result = client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=test.png',
202, actor=actor, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
check(result['status'] == 'queued', '202 must contain queued snapshot')
return result
def state(client, actor, attachment):
return client.call('GET', '/api/v1/attachments/' + attachment['id'], actor=actor, schema='Attachment')['json']
def wait_state(client, actor, attachment, wanted='ready', timeout=100):
def poll():
result = state(client, actor, attachment)
if wanted == 'ready':
check(result['status'] != 'failed', 'job unexpectedly failed')
return result if result['status'] == wanted else None
return wait_for(poll, 'attachment did not become ' + wanted, timeout)
def fault(point):
check(point in ('dispatcher_before_publish','dispatcher_after_publish','worker_after_claim','worker_after_objects','worker_before_ack'),'unknown fault point')
psql("INSERT INTO pipeline_faults(point) VALUES('"+point+"') ON CONFLICT(point) DO UPDATE SET armed=true,hit_at=NULL;")
def hit(point):
wait_for(lambda: psql("SELECT hit_at IS NOT NULL FROM pipeline_faults WHERE point='" + point + "';") == 't',
'fault not reached: ' + point)
def dump_evidence(name, value):
(ROOT / 'evidence').mkdir(exist_ok=True)
(ROOT / 'evidence' / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
def start_only(service):
# Compose start can also start dependencies; fault tests need exactly this container.
container = compose('ps', '--all', '-q', service)
result = subprocess.run(['docker', 'start', container], capture_output=True, text=True)
check(result.returncode == 0, 'cannot start container ' + service)
+49
View File
@@ -0,0 +1,49 @@
"""Operator TLS/policy audit inside an ephemeral container; outputs no credentials."""
import http.client,json,socket,ssl
from pathlib import Path
BASE=Path('/audit');results={}
def context(role):
c=ssl.create_default_context(cafile=str(BASE/'public/ca.crt'))
if role:c.load_cert_chain(BASE/'tls'/role/'cert.crt',BASE/'tls'/role/'key.key')
return c
def probe(host,port,role,path='/',payload=None):
c=context(role)
with socket.create_connection((host,port),timeout=3) as raw:
with c.wrap_socket(raw,server_hostname=host) as s:
s.sendall(payload or f'GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n'.encode())
return s.recv(512)
def denied(host,port,role,path='/',payload=None):
try:
response=probe(host,port,role,path,payload)
return not response or response.startswith(b'HTTP/1.1 403') or response.startswith(b'HTTP/1.0 403')
except (OSError,ssl.SSLError):return True
def check(value,label):
if not value:raise AssertionError(label)
results[label]='PASS'
for host,port,role,path,raw in [('api1',8080,'lb','/health/ready',None),('api2',8080,'lb','/health/ready',None),('broker',6379,'worker','/',b'*1\r\n$4\r\nPING\r\n'),('otel-collector',4318,'worker','/',None)]:
check(bool(probe(host,port,role,path,raw)),host+'_authorized_identity')
check(denied(host,port,None,path,raw),host+'_no_certificate_denied')
check(denied(host,port,'foreign',path,raw),host+'_foreign_CA_denied')
check(denied(host,port,'outsider',path,raw),host+'_trusted_wrong_SAN_denied')
for role in ['api1','api2','dispatcher']:
check(bool(probe('otel-collector',4318,role)),role+'_collector_mTLS')
check(bool(probe('broker',6379,'dispatcher',payload=b'*1\r\n$4\r\nPING\r\n')),'dispatcher_broker_mTLS')
check(denied('broker',6379,'worker',payload=b'*5\r\n$4\r\nXADD\r\n$18\r\nattachment.jobs.v1\r\n$1\r\n*\r\n$3\r\njob\r\n$2\r\n{}\r\n'),'worker_cannot_publish_job_stream')
# TLS matrix positive probes and role denials for each dependency path.
for host,port,role,path in [('redis',6379,'api1','/'),('s3',9000,'worker','/'),('prometheus',9090,'grafana','/-/ready'),('loki',3100,'grafana','/ready'),('tempo',3200,'grafana','/ready')]:
payload=b'*1\r\n$4\r\nPING\r\n' if host=='redis' else None
check(bool(probe(host,port,role,path,payload)),host+'_verified_TLS')
check(denied(host,port,'outsider',path,payload),host+'_outsider_denied')
# Closed local hops cannot be reached through the container network.
for host,port in [('broker',16379),('redis',16379),('s3',19000),('otel-collector',14318),('prometheus',19090),('loki',13100),('tempo',13200)]:
try: socket.create_connection((host,port),timeout=1).close();closed=False
except OSError:closed=True
check(closed,host+'_plaintext_bypass_closed')
# Actual cert login + scoped policy, not just reading policy text.
c=http.client.HTTPSConnection('openbao',8200,context=context('worker'),timeout=5)
c.request('POST','/v1/auth/cert/login',json.dumps({'name':'worker'}),{'Content-Type':'application/json'});r=c.getresponse();auth=json.loads(r.read());check(r.status==200,'bao_cert_login')
token=auth['auth']['client_token'];headers={'X-Vault-Token':token,'Content-Type':'application/json'}
for method,path,status in [('GET','secret/worker',200),('GET','secret/api1',403),('PUT','sys/policies/acl/injected',403)]:
c.request(method,'/v1/'+path,'{}' if method=='PUT' else None,headers);r=c.getresponse();r.read();check(r.status==status,'bao_'+path.replace('/','_')+'_policy')
check(auth['auth']['lease_duration']<=120,'bao_bounded_token_TTL')
print(json.dumps({'status':'PASS','checks':results},indent=2))
+129
View File
@@ -0,0 +1,129 @@
"""Two diagnosed incidents + bounded telemetry outage, using stored observations."""
import concurrent.futures
import datetime
import json
import os
import subprocess
import time
import uuid
from obs_helpers import *
def send_load(client,actor,chat,seconds,workers=2):
deadline=time.monotonic()+seconds
path='/api/v1/chats/'+chat['id']+'/messages'
def task(_):
c=Client(client.base,timeout=8);ok=failed=0;durations=[]
while time.monotonic()<deadline:
begin=time.monotonic()
try:
c.call('POST',path,201,actor=actor,body={'text':'synthetic load'},headers={'Idempotency-Key':uuid.uuid4().hex})
ok+=1;durations.append(time.monotonic()-begin)
except Failure:failed+=1
return ok,failed,durations
start=time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:rows=list(pool.map(task,range(workers)))
elapsed=time.monotonic()-start
durations=sorted(d for r in rows for d in r[2]);count=sum(r[0] for r in rows)
def percentile(fraction):
import math
return round(durations[max(0,math.ceil(len(durations)*fraction)-1)]*1000,3) if durations else None
return dict(seconds=round(elapsed,3),workers=workers,successful_requests=count,failed_requests=sum(r[1] for r in rows),
successful_rps=round(count/elapsed,3),latency_ms_successes={k:percentile(f) for k,f in [('p50',.5),('p95',.95),('p99',.99)]})
def collector_stats():
container=compose('ps','-q','otel-collector')
r=subprocess.run(['docker','stats','--no-stream','--format','{{json .}}',container],capture_output=True,text=True,check=True)
value=json.loads(r.stdout)
return {'memory':value['MemUsage'],'cpu':value['CPUPerc']}
def main():
client=Client(timeout=8);actor,_,_,chat=client.bootstrap()
output={'warmup_load':send_load(client,actor,chat,5)}
try:
# 1. Queue lag: no worker; HTTP remains usable; stored heartbeat reveals cause.
compose('stop','worker');began=time.monotonic()
pending=[upload(client,actor,chat) for _ in range(3)]
wait_for(lambda:alert('MessengerQueueLag')=='firing','queue lag alert did not fire',60)
queue=dict(firing=True,detected_seconds=round(time.monotonic()-began,3),
depth=number('max(messenger_queue_depth)'),oldest_age_seconds=number('max(messenger_queue_oldest_age_seconds)'),
worker_busy=number('max(messenger_worker_busy)'),
worker_heartbeat_age_seconds=number('max(time()-messenger_process_last_observed_seconds{service_name="messenger-worker"})'))
check(queue['depth']>=3 and queue['oldest_age_seconds']>10,'queue metrics do not explain lag')
check(queue['worker_heartbeat_age_seconds']>10,'worker absence not observable')
client.message(actor,chat,'messages continue with worker stopped')
start_only('worker')
for item in pending:wait_state(client,actor,item)
wait_for(lambda:alert('MessengerQueueLag')=='resolved','queue alert did not resolve',40)
queue.update(resolved=True,depth_after=number('max(messenger_queue_depth)'))
output['worker_stopped']=queue
print('PASS: queue lag firing -> resolved, heartbeat stale, backlog drained',flush=True)
# 2. PostgreSQL unavailable; identify dependency spans, not generic slow handler.
compose('stop','postgres');begin=time.monotonic();error_trace=None;errors=0
while time.monotonic()-begin<50:
response=client.call('POST','/api/v1/chats/'+chat['id']+'/messages',503,actor=actor,
body={'text':'synthetic outage'},headers={'Idempotency-Key':uuid.uuid4().hex})
error_trace=response['headers']['X-Trace-Id'];errors+=1
if alert('MessengerHighErrorRate')=='firing' and time.monotonic()-begin>=15:break
check(alert('MessengerHighErrorRate')=='firing','5xx alert did not fire')
database=dict(firing=True,detected_seconds=round(time.monotonic()-begin,3),failed_requests=errors,
error_ratio=number('messenger:api_error_ratio:rate1m'),
db_available=number('min_over_time(messenger_db_available[1m])'),
pool_waiting_peak=number('max(max_over_time(messenger_db_pool_waiting[1m]))'),trace_id=error_trace)
data=wait_for(lambda:trace_data(error_trace),'DB failure trace not stored',25)
children=[s for s in spans(data) if s['name'].startswith('db.')]
check(children,'no DB child span explains HTTP failure')
check(any(s.get('status',{}).get('code') in (2,'STATUS_CODE_ERROR') for s in children),'DB spans lack error status')
check(database['db_available']==0,'DB availability signal did not show outage')
dump_evidence('db-incident-trace.json',data)
compose('start','postgres');ready(client)
# Real recovered traffic, no time-series manipulation.
deadline=time.monotonic()+90
while alert('MessengerHighErrorRate')!='resolved' and time.monotonic()<deadline:
for _ in range(10):client.message(actor,chat,'healthy recovery')
time.sleep(.5)
check(alert('MessengerHighErrorRate')=='resolved','5xx alert did not resolve')
database.update(resolved=True,db_available_after=number('messenger_db_available'))
output['postgres_stopped']=database
print('PASS: DB error spans + 5xx alert firing -> resolved',flush=True)
# 3. A telemetry backend down: business writes still work; buffers are finite.
before_failed=number('sum(otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"})')
before_stats=collector_stats()
since=datetime.datetime.now(datetime.timezone.utc).isoformat()
compose('stop','tempo')
result=send_load(client,actor,chat,20)
check(result['successful_requests']>0 and result['failed_requests']==0,'telemetry backend broke business API')
# wait beyond bounded retry deadline so final drops can be observed.
time.sleep(8)
failed=number('sum(otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"})')-before_failed
queued=number('max(max_over_time(otelcol_exporter_queue_size{exporter="otlphttp/tempo"}[1m]))')
check(failed>0,'Collector failures not observable')
check(queued<=32,'Collector exceeded configured buffer')
after_stats=collector_stats()
raw_logs=compose('logs','--no-log-prefix','--since',since,'otel-collector')
dropped=0
for line in raw_logs.splitlines():
try:record=json.loads(line)
except ValueError:continue
if record.get('otelcol.signal')=='traces':dropped+=int(record.get('dropped_items',0))
check(dropped>0,'actual dropped trace records not counted')
output['tempo_stopped']=dict(workload=result,collector_before=before_stats,collector_during=after_stats,
failed_span_send_records_delta=failed,max_queue_batches=queued,queue_limit_batches=32,
dropped_spans_from_collector_logs=dropped,business_api_preserved=True)
compose('start','tempo')
wait_for(lambda:backend('https://tempo:3200/ready',text=True),'Tempo did not recover',40)
probe=client.call('GET','/api/v1/users/me',actor=actor)
wait_for(lambda:trace_data(probe['headers']['X-Trace-Id']),'traces did not resume',40)
output['tempo_stopped']['export_resumed']=True
print('PASS: telemetry backend outage preserves writes, queues bounded, dropped spans counted',flush=True)
dump_evidence('incidents-grade4.json',output)
finally:
compose('start','postgres','worker','tempo');ready(client)
if __name__=='__main__':
run(main)
+56
View File
@@ -0,0 +1,56 @@
"""Operator lifecycle checks: fresh-connection revocation, secret rotation, sealed lease.
Runs sequentially; restores OpenBao and worker in finally. No secret output.
"""
import json,os,subprocess,time,ssl,urllib.error
from pipeline_helpers import *
def operator(script,*args):
p=subprocess.run(['python3',str(ROOT/'scripts'/script),*args],cwd=ROOT,capture_output=True,text=True)
check(p.returncode==0,'operator action failed: '+script)
def main():
c=Client(timeout=10);actor,_,_,chat=c.bootstrap()
images={s:compose('images','-q',s) for s in ['api1','worker','nginx']}
old=json.loads((ROOT/'secrets/operator/service-secrets.json').read_text())['worker']['DATABASE_URL']
operator('rotate-db-secret.py')
# libpq rejects the previous password on a NEW TLS connection.
from urllib.parse import urlsplit
u=urlsplit(old)
p=subprocess.run(['docker','compose','--env-file','.env','exec','-T','-e','PGPASSWORD','-e','PGSSLMODE=verify-full','-e','PGSSLROOTCERT=/run/ca/ca.crt','postgres','psql','-XAt','-h','postgres','-U','worker','-d','messenger','-c','SELECT 1'],cwd=ROOT,capture_output=True,text=True,env=dict(os.environ,PGPASSWORD=u.password))
check(p.returncode!=0 and 'password authentication failed' in p.stderr,'old secret still authenticates')
item=upload(c,actor,chat);wait_state(c,actor,item)
operator('rotate-leaf.py','worker')
code='''
import socket,ssl
c=ssl.create_default_context(cafile='/audit/public/ca.crt');c.load_cert_chain('/old/cert.crt','/old/key.key')
try:
with socket.create_connection(('broker',6379),timeout=3) as raw:
with c.wrap_socket(raw,server_hostname='broker') as s:
s.sendall(b'*1\\r\\n$4\\r\\nPING\\r\\n');data=s.recv(512)
assert not data,'revoked certificate accepted'
except (OSError,ssl.SSLError):pass
print('PASS')
'''
p=subprocess.run(['docker','compose','--env-file','.env','run','--rm','--no-deps','-v',str(ROOT/'secrets/operator/previous-leaf/worker')+':/old:ro','--entrypoint','python3','audit','-c',code],cwd=ROOT,capture_output=True,text=True)
check(p.returncode==0,'revoked leaf passed fresh connection')
item=upload(c,actor,chat);wait_state(c,actor,item)
# API rejects an expired secret lease while remaining available for /health/live.
started=time.monotonic()
try:
operator('bao-operator.py','seal')
def expired():
try:return c.call('GET','/api/v1/users/me',503,actor=actor)
except Failure:return None
wait_for(expired,'API used credentials beyond bounded sealed lease',90)
elapsed=time.monotonic()-started
c.call('GET','/health/live',schema='Health')
finally:
operator('bao-operator.py','unseal')
compose('start','worker','dispatcher','cleanup')
ready(c)
c.call('GET','/api/v1/users/me',actor=actor,schema='User')
item=upload(c,actor,chat);wait_state(c,actor,item,timeout=120)
check(all(compose('images','-q',s)==image for s,image in images.items()),'rotation rebuilt images')
result={'status':'PASS','old_DB_password_new_connection':'rejected','new_DB_password':'working','leaf_rotation':'worker','old_leaf_new_connection':'rejected','images_unchanged':True,'sealed_lease_rejected_seconds':round(elapsed,3),'unsealed_recovery':True,'original_session_preserved':True}
dump_evidence('lifecycle-grade4.json',result);print('PASS: DB rotation, leaf revocation and sealed/expired secret lease')
if __name__=='__main__':run(main)
+94
View File
@@ -0,0 +1,94 @@
"""Grade 4: real stored signals, W3C chain with retry, dashboard and privacy."""
import base64
import hashlib
import os
import time
import uuid
from obs_helpers import *
def normalized_id(value):
if not value:return ''
if all(c in '0123456789abcdef' for c in value.lower()) and len(value) in (16,32):return value.lower()
return base64.b64decode(value).hex()
def main():
client=Client(timeout=30)
actor,_,_,chat=client.bootstrap()
marker='PRIVATE-BODY-'+uuid.uuid4().hex
client.message(actor,chat,marker)
trace_id=uuid.uuid4().hex
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
try:
compose('stop','worker')
response=client.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=private-canary.png',202,
actor=actor,raw=raw,headers={'Content-Type':'image/png','traceparent':'00-'+trace_id+'-0123456789abcdef-01','tracestate':'lab=synthetic'},schema='Attachment')
item=response['json'];request_id=response['headers']['X-Request-Id']
check(response['headers']['X-Trace-Id']==trace_id,'incoming W3C traceparent not honored')
compose('stop','s3');start_only('worker')
wait_for(lambda: psql("SELECT attempts>=1 AND state='queued' FROM attachment_jobs WHERE id='"+item['id']+"';")=='t','retry not observed',35)
compose('start','s3');ready(client)
wait_state(client,actor,item)
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'original changed')
def linked():
data=trace_data(trace_id);found=spans(data)
names={s['name'] for s in found}
consumers=[s for s in found if s['name']=='attachment.consume']
if len(consumers)>=2 and {'attachment.publish','image.process','s3.put','db.update','db.commit'}.issubset(names):return data
return None
data=wait_for(linked,'complete upload/publish/retry/consume/result trace missing',60)
found=spans(data)
publishers={normalized_id(s['spanId']) for s in found if s['name']=='attachment.publish'}
consumers=[s for s in found if s['name']=='attachment.consume']
check(all(normalized_id(s.get('parentSpanId','')) in publishers for s in consumers),'consumer parent is not producer')
correlated=wait_for(lambda: [entry for entry in logs(trace_id) if entry.get('event')=='job.completed' and entry.get('outcome')=='success'], 'worker log missing',40)
all_logs=logs(trace_id)
events={entry['event'] for entry in all_logs}
check({'http.request','job.published','job.started','job.completed'}.issubset(events),'API/publisher/worker logs not correlated')
check(any(e.get('request_id')==request_id and e['event']=='http.request' for e in all_logs),'request id correlation missing')
check(correlated[0]['request_id']==request_id,'worker lost originating request id')
encoded=json.dumps(data)+json.dumps(all_logs)+json.dumps(logs(service='messenger-api'))
for secret in (marker,actor['token'],actor['registration']['password'],'private-canary.png'):
check(secret not in encoded,'sensitive payload/header/filename entered telemetry')
# Actual stored metric names, not assumptions from SDK naming.
expressions={
'http_requests':'sum(messenger_http_requests_total)',
'http_histogram':'sum(messenger_http_duration_seconds_count)',
'jobs_success':'sum(messenger_jobs_processed_total{outcome="success"})',
'jobs_retry':'sum(messenger_jobs_processed_total{outcome="retry"})',
'ready_histogram':'sum(messenger_time_to_ready_seconds_count)',
'queue':'max(messenger_queue_depth)',
'pool':'max(messenger_db_pool_capacity)',
'worker_capacity':'max(messenger_worker_capacity)',
'memory':'max(messenger_container_memory_bytes)',
}
values={}
for name,expression in expressions.items():
wait_for(lambda: prom(expression),'missing metric '+name,20)
values[name]=number(expression)
check(values['jobs_success']>0 and values['jobs_retry']>0,'worker outcomes absent')
metric_rows=prom('{__name__=~"messenger_.*"}')
forbidden={'user_id','chat_id','message_id','attachment_id','request_id','filename','url','path','job_id'}
check(not any(forbidden.intersection(row['metric']) for row in metric_rows),'high-cardinality metric labels')
password=(ROOT/'secrets/grafana_admin_password').read_text().strip()
code='''
import base64,json,sys,urllib.request
p=sys.stdin.read().strip();req=urllib.request.Request('https://grafana:3000/api/dashboards/uid/mtusi-messenger',headers={'Authorization':'Basic '+base64.b64encode(('admin:'+p).encode()).decode()})
with urllib.request.urlopen(req,timeout=10) as r:d=json.load(r)
print(json.dumps({'title':d['dashboard']['title'],'panels':len(d['dashboard']['panels'])}))
'''
dashboard=json.loads(compose('exec','-T','worker','python3','-c',code,data=password))
check(dashboard['panels']>=18,'provisioned dashboard missing')
dump_evidence('trace-example.json',data)
dump_evidence('correlated-logs.json',all_logs)
output=dict(status='PASS',trace_id=trace_id,request_id=request_id,consumer_attempt_spans=len(consumers),
events=sorted(events),metrics=values,dashboard=dashboard,privacy='PASS',low_cardinality='PASS')
dump_evidence('observability-grade4.json',output)
print('PASS:',json.dumps(output))
finally:
compose('start','s3','worker');ready(client)
if __name__=='__main__':
run(main)
+138
View File
@@ -0,0 +1,138 @@
"""Grade 4: durable acceptance, outbox, crashes, lease, retries, explicit replay."""
import hashlib
import json
import time
import uuid
from pipeline_helpers import *
def main():
client = Client(timeout=30)
ready(client)
actor, _, _, chat = client.bootstrap()
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
results = {}
try:
# Worker absent: no resize in API, accepted job survives real restarts.
compose('stop', 'worker')
attachment = upload(client, actor, chat)
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 409, actor=actor)
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
body={'text': '', 'attachment_ids': [attachment['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')
services = ('api1', 'api2', 'broker')
def starts():
values = {}
for service in services:
container = compose('ps', '-q', service)
data = subprocess.run(['docker', 'inspect', container], capture_output=True, text=True, check=True)
values[service] = json.loads(data.stdout)[0]['State']['StartedAt']
return values
before = starts()
compose('restart', *services)
ready(client)
after = starts()
check(all(before[s] != after[s] for s in services), 'actual restart not observed')
check(state(client, actor, attachment)['status'] == 'queued', 'worker stopped but state changed')
start_only('worker')
result = wait_state(client, actor, attachment)
check({v['name'] for v in result['variants']} == {'thumbnail', 'crop', 'optimized'}, 'missing grade4 variants')
check(client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=actor)['bytes'] == raw, 'original changed')
wait_for(lambda: psql("SELECT staging_deleted_at IS NOT NULL FROM attachment_jobs WHERE id='" + attachment['id'] + "';") == 't', 'staging not cleaned')
results['stopped_worker_and_restart'] = dict(status='PASS', before=before, after=after)
# Committed outbox remains when dispatcher dies before XADD.
compose('stop', 'dispatcher')
fault('dispatcher_before_publish')
item = upload(client, actor, chat)
check(psql("SELECT count(*) FROM attachment_outbox WHERE job_id='" + item['id'] + "';") == '1', 'outbox absent')
compose('start', 'dispatcher')
hit('dispatcher_before_publish')
wait_state(client, actor, item)
results['commit_publish_gap'] = 'PASS: actual dispatcher exit 86 and automatic restart'
# Crash after S3 objects, before final PG COMMIT; reclaim expired processing.
fault('worker_after_objects')
item = upload(client, actor, chat)
hit('worker_after_objects')
check(psql("SELECT state FROM attachment_jobs WHERE id='" + item['id'] + "';") == 'processing', 'crash did not leave processing')
started = time.monotonic()
result = wait_state(client, actor, item, timeout=110)
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == '2', 'expired lease not recovered')
check(len(result['variants']) == 3, 'duplicate variant metadata')
results['crash_after_objects'] = dict(status='PASS', recovery_seconds=round(time.monotonic()-started, 3), attempts=2)
# COMMIT ready then death before ack: ready must never regress/reprocess.
fault('worker_before_ack')
item = upload(client, actor, chat)
hit('worker_before_ack')
result = wait_state(client, actor, item)
attempts = psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';")
duplicate = dict(schema_version=1, job_id=item['id'], type='attachment.process.v1', attachment_id=item['id'],
pipeline_version=1, attempt=1, created_at=item['created_at'])
# Use broker password only inside the container, never in evidence.
duplicate_id = compose('exec', '-T', 'broker', 'sh', '-ec',
'redis-cli -p 16379 --user operator --no-auth-warning -a "$(cat /run/secrets/broker_operator)" XADD attachment.jobs.v1 "*" job "$1"',
'sh', json.dumps(duplicate))
wait_for(lambda: compose('exec', '-T', 'broker', 'sh', '-ec',
'redis-cli -p 16379 --user operator --raw --no-auth-warning -a "$(cat /run/secrets/broker_operator)" XRANGE attachment.jobs.v1 "$1" "$1"',
'sh', duplicate_id) == '', 'ready duplicate was not acknowledged')
check(state(client, actor, item) == result, 'ready duplicate changed result')
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == attempts, 'ready duplicate processed again')
results['commit_before_ack_and_duplicate'] = 'PASS'
# Temporary S3 failure: attempt budget/backoff, failed registry, audited replay.
compose('stop', 'worker')
item = upload(client, actor, chat)
psql("UPDATE attachment_jobs SET max_attempts=2 WHERE id='" + item['id'] + "';")
compose('stop', 's3')
start_only('worker')
check(compose('ps', '--status', 'running', '-q', 's3') == '', 'fault test unexpectedly restarted S3')
wait_for(lambda: psql("SELECT state FROM attachment_jobs WHERE id='" + item['id'] + "';") == 'failed', 'temporary errors did not exhaust retries', 100)
compose('start', 's3')
ready(client)
failed = state(client, actor, item)
check(failed['error_code'] == 'retry_exhausted', 'unsafe or missing final error')
client.call('GET', '/api/v1/attachments/' + item['id'] + '/content', 409, actor=actor)
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=actor,
body={'text':'failed', 'attachment_ids':[item['id']]}, headers={'Idempotency-Key':uuid.uuid4().hex})
registry = compose('exec', '-T', 'dispatcher', '/messenger', 'failed-jobs')
check(item['id'] in registry, 'failed registry missing job')
compose('exec', '-T', 'dispatcher', '/messenger', 'replay', item['id'])
wait_state(client, actor, item)
check(psql("SELECT count(*) FROM attachment_replays WHERE job_id='" + item['id'] + "';") == '1', 'replay audit missing')
proc = subprocess.run(['docker','compose','--env-file','.env','exec','-T','dispatcher','/messenger','replay',item['id']], cwd=ROOT, capture_output=True)
check(proc.returncode != 0, 'ready replay must be refused')
results['retry_failed_registry_replay'] = dict(status='PASS', exhausted_attempts=2, error_code='retry_exhausted', replay_audit_rows=1, ready_replay_rejected=True)
# Permanent invalid staging: no endless retries, safe machine error.
compose('stop', 'worker')
item = upload(client, actor, chat)
original_key = uuid.uuid4().hex
original_body = {'text':'accepted while queued', 'attachment_ids':[item['id']]}
original_message = client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
actor=actor, body=original_body, headers={'Idempotency-Key':original_key}, schema='Message')['json']
# Integrity metadata mismatch represents invalid durable source.
psql("UPDATE attachments SET sha256=repeat('0',64) WHERE id='" + item['id'] + "';")
start_only('worker')
failed = wait_state(client, actor, item, 'failed')
check(failed['error_code'] == 'invalid_image', 'permanent invalid source must fail safely')
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == '1', 'permanent error retried')
repeated = client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
actor=actor, body=original_body, headers={'Idempotency-Key':original_key}, schema='Message')['json']
check(repeated == original_message, 'committed message replay changed after attachment failed')
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409,
actor=actor, body=original_body, headers={'Idempotency-Key':uuid.uuid4().hex})
results['permanent_error'] = 'PASS'
results['message_replay_after_attachment_failure'] = 'PASS'
results['crash_points'] = json.loads(psql("SELECT json_agg(json_build_object('point',point,'armed',armed,'hit_at',hit_at) ORDER BY point) FROM pipeline_faults WHERE hit_at IS NOT NULL;"))
dump_evidence('pipeline-grade4.json', results)
print('PASS:', json.dumps(results))
finally:
compose('start', 's3', 'broker', 'dispatcher', 'worker', 'api1', 'api2')
psql('DELETE FROM pipeline_faults;')
ready(client)
if __name__ == '__main__':
run(main)
+92
View File
@@ -0,0 +1,92 @@
"""Public persistence/failover hooks plus actual container restart evidence."""
import json
import datetime
import subprocess
import uuid
from pipeline_helpers import *
def snapshots():
services=('postgres','redis','s3','broker','api1','api2','dispatcher','worker','cleanup','nginx','otel-collector','prometheus','loki','tempo','grafana','openbao')
result={}
for service in services:
container=compose('ps','-q',service)
info=subprocess.run(['docker','inspect',container],capture_output=True,text=True,check=True)
data=json.loads(info.stdout)[0]
result[service]=dict(id=data['Id'],started_at=data['State']['StartedAt'])
return result
def main():
client=Client();ready(client)
before=snapshots()
base=client.base
command=['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+base,'CA_FILE='+str(ROOT/'secrets/public/ca.crt')]
result=subprocess.run(command,cwd=ROOT,capture_output=True,text=True)
check(result.returncode==0,'public persistence failed: '+result.stdout[-500:])
after=snapshots()
check(all(before[s]['started_at']!=after[s]['started_at'] for s in before),'hook did not restart all required services')
output={'persistence':dict(status='PASS',before=before,after=after),'failover':[]}
public=subprocess.run(['make','test-failover','ACTION_SCRIPT=scripts/stop-one.sh','BASE_URL='+base,'CA_FILE='+str(ROOT/'secrets/public/ca.crt')],cwd=ROOT,capture_output=True,text=True)
check(public.returncode==0,'public failover failed: '+public.stdout[-500:])
output['public_failover']=dict(status='PASS',output=public.stdout.strip())
try:
compose('start','api1','api2');ready(client)
actor,_,_,chat=client.bootstrap()
item=upload(client,actor,chat);wait_state(client,actor,item)
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
path='/api/v1/chats/'+chat['id']+'/messages'
for target in ('api-1','api-2'):
compose('start','api1','api2');ready(client)
seen=set()
wait_for(lambda: (seen.add(client.call('GET','/health/ready')['headers']['X-Instance-Id']) or len(seen)==2),'two replicas not visible')
process=subprocess.Popen([str(ROOT/'scripts/stop-one.sh')],cwd=ROOT,
env=dict(os.environ,TARGET_INSTANCE_ID=target),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
began=time.monotonic();deadline=began+8;first=None;confirmed=set();failures=0
key=uuid.uuid4().hex
while time.monotonic()<deadline:
try:
response=client.call('POST',path,201,actor=actor,body={'text':key},headers={'Idempotency-Key':key},schema='Message')
confirmed.add(response['json']['id'])
if process.poll() is not None and response['headers']['X-Instance-Id']!=target and first is None:
first=time.monotonic()-began
key=uuid.uuid4().hex
except Failure:
failures+=1
time.sleep(.1)
check(process.wait(timeout=10)==0,'stop hook failed')
check(first is not None and first<=10,'surviving API did not recover within 10 seconds')
service={'api-1':'api1','api-2':'api2'}[target]
check(not compose('ps','--status','running','-q',service),'target was not actually stopped')
page=client.call('GET',path+'?limit=100',actor=actor,schema='MessagePage')['json']
visible={m['id'] for m in page['items']}
# At most 80 requests per case: walk pages to include both cases.
while page['next_cursor']:
from urllib.parse import quote
page=client.call('GET',path+'?limit=100&cursor='+quote(page['next_cursor']),actor=actor,schema='MessagePage')['json']
visible.update(m['id'] for m in page['items'])
check(confirmed.issubset(visible),'confirmed messages lost')
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'original lost on API failover')
output['failover'].append(dict(status='PASS',stopped_service=service,confirmed_messages=len(confirmed),
transient_failures=failures,first_survivor_seconds=round(first,3),original_preserved=True))
finally:
compose('start','api1','api2');ready(client)
saved=ROOT/'evidence/observability-grade4.json'
if saved.exists():
from obs_helpers import trace_data, logs, number
trace_id=json.loads(saved.read_text())['trace_id']
wait_for(lambda:trace_data(trace_id),'stored trace lost after telemetry restart',60)
wait_for(lambda:logs(trace_id),'stored logs lost after telemetry restart',60)
check(number('sum(messenger_http_requests_total)')>0,'metrics unavailable after restart')
stamp=datetime.datetime.fromisoformat(after['prometheus']['started_at'].replace('Z','+00:00')).timestamp()-10
historical=number('sum(messenger_http_requests_total @ '+str(stamp)+')')
check(historical>0,'historical metrics lost after Prometheus restart')
output['metric_history_before_restart']={'unix_time':stamp,'http_counter_sum':historical}
output['telemetry_history_preserved']=True
dump_evidence('resilience.json',output)
print('PASS: all core/telemetry/OpenBao services restarted, same token/data/original preserved; both API failures covered')
if __name__=='__main__':
run(main)
+53
View File
@@ -0,0 +1,53 @@
"""HTTPS ACL, Argon migration, shared rate limit and session revocation."""
import base64,hashlib,json,os,ssl,time,uuid
from pipeline_helpers import *
def basic(u,p):return {'Authorization':'Basic '+base64.b64encode((u+':'+p).encode()).decode()}
def main():
c=Client();actor,_,outsider,chat=c.bootstrap();raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
item=upload(c,actor,chat);wait_state(c,actor,item)
c.call('GET','/api/v1/attachments/'+item['id'],404,actor=outsider)
c.call('GET','/api/v1/attachments/'+item['id']+'/content',404,actor=outsider)
c.call('GET','/api/v1/users/me',actor=outsider,headers={'X-User-Id':actor['id']},schema='User')
own=c.call('GET','/api/v1/users/me',actor=outsider,headers={'X-User-Id':actor['id']},schema='User')['json']
check(own['id']==outsider['id'],'spoofed identity accepted')
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=forbidden.png',404,actor=outsider,raw=raw,headers={'Content-Type':'image/png'})
stored=psql("SELECT password_hash FROM users WHERE id='"+actor['id']+"';")
check(stored.startswith('$argon2id$v=19$m=19456,t=2,p=1$'),'Argon2id parameters missing')
# Actual legacy scrypt row, followed by real Basic login and persisted rehash.
reg=actor['registration'];salt=os.urandom(16)
digest=hashlib.scrypt(reg['password'].encode(),salt=salt,n=32768,r=8,p=1,dklen=32,maxmem=64*1024*1024)
enc=lambda b:base64.b64encode(b).decode().rstrip('=')
legacy='scrypt$32768$8$1$'+enc(salt)+'$'+enc(digest)
psql("UPDATE users SET password_hash='"+legacy+"' WHERE id='"+actor['id']+"';")
began=time.monotonic();c.call('POST','/api/v1/auth/sessions',201,headers=basic(reg['username'],reg['password']))
rehash_ms=(time.monotonic()-began)*1000
check(psql("SELECT password_hash LIKE '$argon2id$%' FROM users WHERE id='"+actor['id']+"';")=='t','successful login did not rehash legacy')
# Only a hash of the bearer token is a session key.
expected='session:'+hashlib.sha256(actor['token'].encode()).hexdigest()
check(actor['token'] not in stored,'password storage leaked bearer')
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=actor)
c.call('GET','/api/v1/users/me',401,actor=actor)
# Actual Redis expiry on the existing session; operator shortens only this synthetic key.
key='session:'+hashlib.sha256(outsider['token'].encode()).hexdigest()
compose('exec','-T','redis','sh','-ec','redis-cli -p 16379 --user operator --no-auth-warning -a "$(cat /run/secrets/redis_operator)" EXPIRE "$1" 1','sh',key)
time.sleep(2)
c.call('GET','/api/v1/users/me',401,actor=outsider)
# A repeated username shares its budget across both LB backends.
identity='limit_'+uuid.uuid4().hex[:12];seen=set();throttled=[]
for i in range(16):
r=c.call('POST','/api/v1/auth/sessions',[401,429],headers=basic(identity,'wrong'))
seen.add(r['headers']['X-Instance-Id'])
if r['status']==429:
check(int(r['headers']['Retry-After'])>0,'Retry-After missing');throttled.append(i)
check(len(seen)==2 and throttled and throttled[0]==10,'rate budget is not shared across replicas')
# The CA is trusted, but this hostname must still be rejected.
try:
import socket
with socket.create_connection(('localhost',8443),timeout=3) as sock:
ssl.create_default_context(cafile=str(ROOT/'secrets/public/ca.crt')).wrap_socket(sock,server_hostname='wrong.invalid')
raise Failure('wrong hostname accepted')
except ssl.SSLCertVerificationError:pass
result={'status':'PASS','argon2id':'m=19456KiB,t=2,p=1','legacy_rehash_ms':round(rehash_ms,3),'outsider_metadata_content_upload':'denied','spoofed_header':'ignored','logout':'401','session_expiry':'401','shared_rate_limit_first_429_attempt':throttled[0]+1,'api_instances':sorted(seen),'hostname_mismatch':'rejected'}
dump_evidence('security-grade4.json',result);print('PASS: HTTPS ACL, real legacy rehash, logout and shared rate limit')
if __name__=='__main__':run(main)
+29
View File
@@ -0,0 +1,29 @@
"""Operator internal TLS/policy and runtime hardening audit; no Config.Env dump."""
import subprocess
from pipeline_helpers import *
def main():
result = json.loads(compose('run', '--rm', '--no-deps', 'audit'))
check(result['status'] == 'PASS', 'TLS matrix audit failed')
controls = {}
for service in ['api1', 'api2', 'worker', 'dispatcher', 'cleanup', 'otel-collector', 'prometheus', 'loki', 'tempo', 'grafana', 'nginx']:
container = compose('ps', '-q', service)
info = json.loads(subprocess.check_output(['docker', 'inspect', container], text=True))[0]
h = info['HostConfig']
check(not h['Privileged'] and h['NetworkMode'] != 'host', 'unsafe container privilege')
check(h['ReadonlyRootfs'] and 'ALL' in h['CapDrop'], 'missing read_only/cap_drop')
check(any('no-new-privileges' in x for x in h['SecurityOpt']), 'missing no-new-privileges')
check(h['Memory'] > 0 and h['NanoCpus'] > 0, 'missing resource limit')
check(not any('docker.sock' in m['Source'] for m in info['Mounts']), 'Docker socket exposed')
if service in ['api1', 'api2', 'worker', 'dispatcher', 'cleanup']:
check(info['Config']['User'].split(':')[0] not in ('', '0', 'root'), 'application runs as root')
check(not any('/secrets/operator' in m['Source'] for m in info['Mounts']), 'operator material exposed')
controls[service] = 'PASS'
result['runtime_hardening'] = controls
dump_evidence('tls-matrix-grade4.json', result)
print('PASS: TLS/mTLS matrix, denied identities, closed plaintext hops, scoped Bao and runtime hardening')
if __name__ == '__main__':
run(main)
+100
View File
@@ -0,0 +1,100 @@
"""Grade 4 image contract: actual decoding, EXIF, alpha, limits and private storage."""
import base64
import hashlib
import json
import struct
import uuid
import zlib
from pipeline_helpers import *
def make_fixture(kind):
code = '''
import base64,io,sys
from PIL import Image
kind=sys.argv[1]
if kind=='orientation':
im=Image.new('RGB',(320,200),'red');exif=Image.Exif();exif[274]=6;exif[315]='synthetic test';kw=dict(format='JPEG',exif=exif)
elif kind=='alpha':
im=Image.new('RGBA',(8,4),(255,0,0,0));kw=dict(format='PNG')
elif kind=='boundary':
im=Image.new('RGB',(8000,5000),'blue');kw=dict(format='PNG')
else:
im=Image.new('RGB',(1601,801),'blue');kw=dict(format='PNG')
b=io.BytesIO();im.save(b,**kw);print(base64.b64encode(b.getvalue()).decode())
'''
return base64.b64decode(compose('exec', '-T', 'worker', 'python3', '-c', code, kind))
def inspect_image(raw):
code = '''
import base64,io,json,sys
from PIL import Image
im=Image.open(io.BytesIO(base64.b64decode(sys.stdin.read())));im.load()
print(json.dumps(dict(format=im.format,width=im.width,height=im.height,exif=len(im.getexif()),pixel=list(im.convert('RGB').getpixel((0,0))))))
'''
return json.loads(compose('exec', '-T', 'worker', 'python3', '-c', code, data=base64.b64encode(raw).decode()))
def chunk(kind, payload):
return struct.pack('>I', len(payload)) + kind + payload + struct.pack('>I', zlib.crc32(kind+payload) & 0xffffffff)
def main():
client=Client(timeout=60)
actor, _, outsider, chat=client.bootstrap()
results={}
for kind in ('orientation','alpha','large','boundary'):
raw=make_fixture(kind)
content_type='image/jpeg' if kind=='orientation' else 'image/png'
item=client.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=synthetic',202,actor=actor,raw=raw,
headers={'Content-Type':content_type},schema='Attachment')['json']
result=wait_state(client,actor,item)
variants={v['name']:v for v in result['variants']}
expected={'orientation':(160,256),'alpha':(8,4),'large':(256,128),'boundary':(256,160)}[kind]
check((variants['thumbnail']['width'],variants['thumbnail']['height'])==expected,'thumbnail dimensions/orientation')
check((variants['crop']['width'],variants['crop']['height'])==(128,128),'crop dimensions')
optimized={'orientation':(200,320),'alpha':(8,4),'large':(1280,640),'boundary':(1280,800)}[kind]
check((variants['optimized']['width'],variants['optimized']['height'])==optimized,'optimized fit dimensions')
for name,meta in variants.items():
blob=client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant='+name,actor=actor)['bytes']
check(hashlib.sha256(blob).hexdigest()==meta['sha256'] and len(blob)==meta['size_bytes'],'variant checksum/size')
decoded=inspect_image(blob)
check(decoded['format']==('WEBP' if name=='optimized' else 'JPEG'),'actual variant encoding')
check(decoded['exif']==0,'EXIF leaked into variant')
if kind=='alpha':
check(all(v>=250 for v in decoded['pixel']),'alpha not composited on white')
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'original changed')
client.call('GET','/api/v1/attachments/'+item['id'],404,actor=outsider)
client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant=crop',404,actor=outsider)
client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant=missing',404,actor=actor)
results[kind]={'status':'PASS','variants':variants}
original=(ROOT/'tests/fixtures/sample.png').read_bytes()
for size in (6294458,10485760):
extra=size-len(original)-12
raw=original[:-12]+chunk(b'paDd',bytes(extra))+original[-12:]
check(len(raw)==size,'fixture exact size')
item=upload(client,actor,chat,raw)
wait_state(client,actor,item)
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'large original changed')
path='/api/v1/chats/'+chat['id']+'/attachments?filename=bad.png'
client.call('POST',path,413,actor=actor,raw=bytes(10485761),headers={'Content-Type':'image/png'})
for raw in (original[:40],original[:-12],b'not an image'):
client.call('POST',path,415,actor=actor,raw=raw,headers={'Content-Type':'image/png'})
huge=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',20000,10000,8,2,0,0,0))+chunk(b'IEND',b'')
client.call('POST',path,413,actor=actor,raw=huge,headers={'Content-Type':'image/png'})
results['byte_limits_corrupt_pixel_limits']='PASS'
item=upload(client,actor,chat)
wait_state(client,actor,item)
audit=compose('exec','-T','api1','/messenger','s3-audit','originals/'+item['id'])
check('PASS' in audit,'S3 credential audit failed')
results['private_bucket_limited_credentials']='PASS'
metrics=json.loads(compose('exec','-T','worker','/messenger','memory'))
check(metrics['memory.peak'] < metrics['memory.max'],'worker reached memory limit')
results['worker_memory_bytes']=metrics
dump_evidence('variants-grade4.json',results)
print('PASS: actual JPEG/WebP, EXIF orientation, white alpha, bounds, ACL, checksums, private S3')
if __name__=='__main__':
run(main)
+60
View File
@@ -0,0 +1,60 @@
"""Bounded subprocess: trusted local paths, no URLs, no credentials."""
import hashlib
import json
import resource
import sys
import warnings
from pathlib import Path
from PIL import Image, ImageOps, UnidentifiedImageError
# Bound decoder subprocess independently of container and Go memory.
resource.setrlimit(resource.RLIMIT_AS, (1024 * 1024 * 1024, 1024 * 1024 * 1024))
Image.MAX_IMAGE_PIXELS = 40_000_000
warnings.simplefilter('error', Image.DecompressionBombWarning)
def contain(image, bound):
w, h = image.size
if max(w, h) <= bound:
return image.copy()
if w >= h:
size = (bound, max(1, h * bound // w))
else:
size = (max(1, w * bound // h), bound)
return image.resize(size, Image.Resampling.LANCZOS)
def main():
source, target = map(Path, sys.argv[1:3])
if source.stat().st_size > 10_485_760:
raise ValueError('size')
with Image.open(source) as original:
if original.format not in ('PNG', 'JPEG') or original.width * original.height > 40_000_000:
raise ValueError('format or pixels')
original.load()
oriented = ImageOps.exif_transpose(original)
rgba = oriented.convert('RGBA')
image = Image.new('RGB', rgba.size, 'white')
image.paste(rgba, mask=rgba.getchannel('A'))
# New pixel images + empty info ensure EXIF/ICC/text are never propagated.
variants = []
for name, result, kind, quality in (
('thumbnail', contain(image, 256), 'JPEG', 85),
('crop', ImageOps.fit(image, (128, 128), method=Image.Resampling.LANCZOS, centering=(.5, .5)), 'JPEG', 85),
('optimized', contain(image, 1280), 'WEBP', 80),
):
result.info.clear()
path = target / name
result.save(path, format=kind, quality=quality, **({'method': 4} if kind == 'WEBP' else {}))
data = path.read_bytes()
variants.append(dict(name=name, content_type='image/webp' if kind == 'WEBP' else 'image/jpeg',
size_bytes=len(data), width=result.width, height=result.height,
sha256=hashlib.sha256(data).hexdigest()))
print(json.dumps(variants))
if __name__ == '__main__':
try:
main()
except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError, Image.DecompressionBombWarning):
sys.exit(2) # permanent invalid_image; details never reach public API