на оценку 4
Skeleton contracts / contracts (pull_request) Blocked by required conditions

This commit is contained in:
2026-11-22 23:33:11 +03:00
parent 20afc2c790
commit cc41f601e3
207 changed files with 22098 additions and 120 deletions
+16 -37
View File
@@ -1,41 +1,20 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
# These are logical interface suggestions; map actual framework names in REPORT.md.
APP_HOST=0.0.0.0
APP_PORT=8080
APP_ENV=lab
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
# Optional non-secret overrides for the local synthetic lab7 stand.
# Credentials, private keys and AppRole SecretIDs are generated under ignored
# secrets/ and .operator/ directories by `make init-secrets` / `make bootstrap`.
HTTPS_PORT=8443
OPENBAO_PORT=18200
GRAFANA_PORT=13000
PROMETHEUS_PORT=19090
LOKI_PORT=13100
TEMPO_PORT=13200
API_REPLICAS=2
IDEMPOTENCY_TTL_SECONDS=86400
S3_ENDPOINT=https://s3:9000
S3_REGION=us-east-1
S3_BUCKET=messenger-attachments
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000
BROKER_URL_FILE=/run/secrets/broker_url
WORKER_CONCURRENCY=2
JOB_MAX_ATTEMPTS=5
JOB_TIMEOUT_SECONDS=60
STAGING_RETENTION_SECONDS=86400
OTEL_SERVICE_NAME=messenger-api
# Worker must set a distinct service.name.
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix.
PUBLIC_BASE_URL=https://localhost:8443
TLS_CA_FILE=/run/secrets/ca.crt
TLS_CERT_FILE=/run/secrets/service.crt
TLS_KEY_FILE=/run/secrets/service.key
BAO_ADDR=https://openbao:8200
BAO_CACERT=/run/secrets/bao-ca.crt
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
SESSION_TTL_SECONDS=3600
LOGIN_RATE_LIMIT=5
LOGIN_RATE_WINDOW_SECONDS=60
# Grade-3 floor. Lower values are rejected by the application.
ARGON2_MEMORY_KIB=19456
ARGON2_ITERATIONS=2
ARGON2_PARALLELISM=1
+14 -14
View File
@@ -1,18 +1,18 @@
## Лабораторная 7
Автор / группа: TODO
Целевая оценка (3/4/5): TODO
Трек 5, если заявлен: TODO
Автор / группа: Чурилин Данила / БВТ2301
Целевая оценка (3/4/5): 4
Трек 5, если заявлен: не заявлен
Что реализовано и что перенесено: TODO
Команды запуска из чистого clone: TODO
Результаты проверок и ссылка на REPORT.md: TODO
Ограничения / известные ошибки: TODO
Источники и использование ИИ: TODO
Что реализовано и что перенесено: возможности lab6 перенесены без ослабления; добавлены TLS/mTLS trust boundaries, least-privilege ACL, OpenBao AppRole lifecycle, password rehash и общий login limiter, runtime hardening, secret/leaf rotation, telemetry leak audit и dependency/image scan.
Команды запуска из чистого clone: `make up`, затем `make test`, `make test-security-grade4`, `make test-acl-grade4`, `make test-telemetry-leak-grade4`; полный список — в `REPORT.md`.
Результаты проверок и ссылка на REPORT.md: воспроизводимые команды, фактические результаты и ограничения приведены в `REPORT.md`, `evidence/grade3-summary.md` и `evidence/grade4-summary.md`.
Ограничения / известные ошибки: single-host стенд; stateful stores и CA не HA; нет background renewal agent, CA rollover, CRL/OCSP, KMS/HSM и уровня 5.
Источники и использование ИИ: Go standard library и зависимости из `go.mod`; версии инфраструктуры из `compose.yaml`; OpenAI Codex использовался для переноса и подготовки решения, результат проверен перечисленными тестами.
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [ ] Контракт и публичные тесты не ослаблены.
- [ ] make check и make test выполнены; приложен реальный вывод.
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [x] Контракт и публичные тесты не ослаблены.
- [x] make check и make test выполнены; приложен реальный вывод.
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
+2
View File
@@ -3,6 +3,7 @@
.env.*
!.env.example
secrets/
.operator/
certs/private/
*.key
*.p12
@@ -15,6 +16,7 @@ data/
backups/
# Runtime/build artifacts
.venv/
.cache/
__pycache__/
*.py[cod]
node_modules/
+42
View File
@@ -0,0 +1,42 @@
FROM golang:1.27.3-alpine@sha256:fa3d596898d9f126af7c01d14ee7597bab3f39cccf392ef36b69fe77cd681f18 AS builder
WORKDIR /build
COPY go.mod go.sum ./
RUN go mod download
COPY cmd/ ./cmd/
COPY internal/ ./internal/
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/server ./cmd/server/main.go
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/reconciler ./cmd/reconciler/main.go
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/worker ./cmd/worker/main.go
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/dispatcher ./cmd/dispatcher/main.go
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/jobctl ./cmd/jobctl/main.go
FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
RUN apk upgrade --no-cache && \
apk add --no-cache ca-certificates curl openssl
RUN addgroup -g 1000 appgroup && \
adduser -u 1000 -G appgroup -s /bin/sh -D appuser
WORKDIR /app
COPY --from=builder /build/server /app/server
COPY --from=builder /build/reconciler /app/reconciler
COPY --from=builder /build/worker /app/worker
COPY --from=builder /build/dispatcher /app/dispatcher
COPY --from=builder /build/jobctl /app/jobctl
RUN chown -R appuser:appgroup /app
USER appuser:appgroup
EXPOSE 8444
ENTRYPOINT ["/app/server"]
+66 -8
View File
@@ -1,13 +1,29 @@
PYTHON ?= python3
BASE_URL ?= https://localhost:8443
CA_FILE ?=
BASE_URL ?= https://127.0.0.1:8443
CA_FILE ?= secrets/pki/ca.crt
ACTION_SCRIPT ?=
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
.PHONY: help check validate test load test-persistence test-failover test-security
.PHONY: help init-secrets bootstrap up down check validate test load test-security test-security-grade3 test-security-grade4 test-acl-grade4 test-state-pruning-grade4 test-telemetry-leak-grade4 test-rate-limit-grade3 test-openbao-policy test-openbao-lifecycle-grade4 rotate-secret-grade4 rotate-leaf-grade4 scan-grade4 test-persistence test-failover argon2-benchmark login-dos-benchmark cleanup-lab
help:
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
@echo "init-secrets, bootstrap, up, down, check, validate, test, load"
@echo "test-security-grade3, test-security-grade4, test-acl-grade4, test-state-pruning-grade4"
@echo "test-rate-limit-grade3, test-openbao-policy, test-openbao-lifecycle-grade4"
@echo "rotate-secret-grade4, rotate-leaf-grade4, scan-grade4, cleanup-lab"
init-secrets:
./scripts/init-secrets.sh
bootstrap: init-secrets
./scripts/bootstrap-dependencies.sh
./scripts/bootstrap-openbao.sh
up: bootstrap
docker compose up -d --build
down:
docker compose down --remove-orphans
check:
$(PYTHON) scripts/check_contract.py
@@ -21,13 +37,55 @@ test:
load:
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-security:
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-security-grade3:
./tests/security_grade3.sh
test-security-grade4:
./tests/security_grade4.sh
test-acl-grade4:
./tests/acl_audit_grade4.sh
test-state-pruning-grade4:
./tests/state_pruning_grade4.sh
test-telemetry-leak-grade4:
./tests/telemetry_leak_grade4.sh
test-rate-limit-grade3:
$(PYTHON) tests/rate_limit_grade3.py --base-url "$(BASE_URL)" $(TLS_ARGS)
test-openbao-policy:
./tests/openbao_policy.sh
test-openbao-lifecycle-grade4:
./tests/openbao_lifecycle_grade4.sh
rotate-secret-grade4:
./scripts/rotate-secret-grade4.sh
rotate-leaf-grade4:
./scripts/rotate-leaf-grade4.sh
scan-grade4:
./scripts/scan-grade4.sh
test-persistence:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT=scripts/restart.sh"; exit 2)
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-failover:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT=scripts/stop-one.sh"; exit 2)
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
test-security:
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
argon2-benchmark:
go test -run '^$$' -bench BenchmarkHashPasswordGrade3 -benchtime=5x ./internal/security
login-dos-benchmark:
go test -run '^$$' -bench BenchmarkVerifyPasswordGrade4 -benchtime=20x ./internal/security
cleanup-lab:
./scripts/cleanup-lab.sh
+99 -15
View File
@@ -1,37 +1,121 @@
# Отчёт — лабораторная 7
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Автор, группа: Чурилин Данила, БВТ2301.
- Целевая оценка: 4. Трек оценки 5 не заявлен и не реализовывался.
- Ветка: `solution/bvt2301-churilin`. Commit/PR не создавались по условию локальной подготовки.
- Использованные источники и ПО: Go standard library; зависимости из `go.mod`; PostgreSQL, Redis, MinIO, RabbitMQ, HAProxy, OpenBao, OpenTelemetry Collector, Prometheus, Loki, Tempo и Grafana в версиях из `compose.yaml`. Для переноса собственной реализации lab6 и подготовки lab7 использовался OpenAI Codex; результат проверен тестами ниже.
## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
Проверенный стенд: Ubuntu/WSL2, Go 1.27.4, Docker Engine 29.7.2, Docker Compose 5.5.0, OpenSSL 3.5.5. Нужны также Python 3 и GNU Make. Полная OpenAPI-валидация требует отдельного Python virtualenv:
```sh
python3 -m venv .venv
.venv/bin/pip install -r requirements-dev.txt
make check
PYTHON=.venv/bin/python make validate
```
Локальные ключи, пароли и operator material создаются вне Git. Значения не нужно записывать в `.env`; файл содержит только необязательные несекретные overrides.
```sh
cp .env.example .env # необязательно
make up # init secrets, bootstrap stores/OpenBao, build, start
make test
make test-security
make test-security-grade3
make test-security-grade4
make test-acl-grade4
make test-telemetry-leak-grade4
make test-rate-limit-grade3
make test-state-pruning-grade4
make test-openbao-policy
make test-openbao-lifecycle-grade4
make rotate-secret-grade4
make rotate-leaf-grade4
make scan-grade4
./tests/minio_policy.sh
```
`make up` повторяем: миграции, bucket/policies, RabbitMQ ACL и AppRole настраиваются идемпотентно. При первом запуске `scripts/bootstrap-openbao.sh` инициализирует non-dev OpenBao. Root token и единственный unseal share сохраняются только в игнорируемом `.operator/openbao-init.json` с mode 0600. После перезапуска OpenBao оператор вручную запускает этот скрипт или `scripts/restart.sh`; приложения unseal/root material не получают.
Внешний API: `https://127.0.0.1:8443`; CA: `secrets/pki/ca.crt`. Локальные интерфейсы: OpenBao `18200`, Grafana `13000`, Prometheus `19090`, Loki `13100`, Tempo `13200`. Последние три требуют допустимый клиентский сертификат; Grafana требует логин; S3/RabbitMQ/Redis/PostgreSQL наружу не опубликованы.
Безопасная остановка сохраняет named volumes и OpenBao file storage:
```sh
make down
```
`make cleanup-lab` дополнительно удаляет только четыре локально собранных образа с префиксом `mtusi2026lab7`, но сохраняет данные и сторонние образы. Намеренное удаление учебных named volumes выполняется отдельно командой `docker compose down -v --remove-orphans`; ignored-каталоги `volumes/openbao`, `secrets` и `.operator` удаляются оператором только после отдельной проверки абсолютного пути и создания нужной резервной копии.
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
Путь запроса: клиент — TLS 1.3 → HAProxy ingress — mTLS 1.3 → две API-реплики. Ingress проверяет DNS SAN `api`, API проверяет CA клиента и точную URI SAN allowlist из отдельного runtime-файла. Это позволяет удалить старую LB identity и принять новый leaf без пересборки image. Порт API 8444 только `expose`, host binding отсутствует. Случайный hostname не используется как публичный instance id: каждая реплика создаёт непрозрачный `api-<random>` в `/tmp/instance-id`.
PostgreSQL остаётся источником истины для пользователей, сессий, сообщений, idempotency, вложений, job и общего login limiter. Транзакции, миграции 1–8 и outbox/job state machine перенесены из lab6; добавлена таблица `login_rate_limits`. Истёкшие sessions/idempotency/limiter rows удаляются индексированными batch по 256 записей: первый раз после запуска и далее амортизированно раз в 128 операций. Для limiter cutoff равен `now - LOGIN_RATE_WINDOW`, поэтому активное окно не сбрасывается. Redis используется только как cache с ACL. S3 и RabbitMQ сохраняют раздельные API/worker и dispatcher/worker credentials.
Продукты без native TLS в выбранной конфигурации доступны только через HAProxy TLS gateway. Plaintext backend hop находится на отдельной `internal: true` сети, где присутствуют только gateway и конкретный backend; обходной порт не опубликован. PostgreSQL и OpenBao используют native TLS. Dispatcher/worker → RabbitMQ и API/worker/dispatcher → OTLP Collector требуют mTLS: у `api`, `worker`, `dispatcher` разные clientAuth leaf, HAProxy проверяет CA и точный CN ACL; same-CA `intruder` получает отказ. API напрямую не использует broker: transactional outbox публикует отдельный `dispatcher`, поэтому API identity на broker намеренно запрещена. Collector → Loki/Tempo, Prometheus → Collector и Grafana → data sources также используют mTLS с отдельными CN/URI identities. Полное сопоставление находится в `contracts/trust-matrix.md`.
OpenBao 2.4.4 работает с file storage `volumes/openbao`, TLS 1.3 и AppRole `api`, `worker`, `dispatcher`. Каждая policy читает только `secret/data/<role>`. App token: TTL 15 минут, max TTL 30 минут; SecretID: 168 часов. Приложение использует token только для стартового чтения allowlisted ключей и не хранит root token.
Пароли хешируются Argon2id с индивидуальными 16-byte salt и параметрами внутри PHC-строки. Минимум, который код не позволяет понизить: `m=19456 KiB, t=2, p=1`. После успешной проверки legacy PHC параметры сравниваются с текущей policy; hash заменяется новым через compare-and-set, не меняя результат параллельного login. Session token хранится только как SHA-256 hash. Unknown user и wrong password имеют одинаковые status/challenge/code/message/длину тела; ошибки credential state не возвращают hash/credential details. Измеренный verify — 23.485943 ms/op; limiter выполняется до Argon2 и допускает 5 попыток на normalized username за 60 s, то есть около 117 ms Argon2 CPU/min на один identifier на этом CPU. Limiter атомарно обновляется в PostgreSQL и общий для обеих реплик; шестая попытка получает 429 и `Retry-After`.
App/worker/dispatcher запускаются UID 1000 с read-only rootfs, `no-new-privileges`, `cap_drop: ALL`, отдельным tmpfs `/tmp` (`nosuid,nodev,noexec`) и CPU/RAM limits. Worker имеет 1 CPU, 512 MiB, `GOMEMLIMIT=448MiB`, timeout 60 s и concurrency 1: две параллельные полные декодировки разрешённых 40-мегапиксельных изображений не конкурируют за один CPU и memory cgroup. Те же read-only/no-new-privileges controls применены к stateless ingress/gateways и Collector. Stateful PostgreSQL/MinIO/RabbitMQ/Loki/Tempo/Prometheus/Grafana/OpenBao сохраняют writable только свои data volumes: это совместимые исключения, а не writable application rootfs. Нет `privileged`, host network или Docker socket. Secret values не входят в image layers и проверяются на отсутствие в Loki. `.env.example` соответствует параметрам портов, числа реплик, TTL, rate limit и Argon2.
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
| Контракт и OpenAPI | `make check`; `PYTHON=.venv/bin/python make validate` | обе проверки PASS | `scripts/check_contract.py`, `scripts/validate_openapi.py` |
| Предыдущие возможности через HTTPS | `make test` | `PASS: lab7 public API scenario` включая auth, ACL, idempotency, S3/worker и logout | `tests/smoke.py` |
| Доверенный/недоверенный внешний TLS | `make test-security` | правильный CA проходит; пустой trust store даёт certificate verification error | `tests/security.py` |
| LB → API mTLS и отсутствие обхода | `make test-security-grade3` | no cert, foreign CA и wrong same-CA identity отклонены; LB identity принята; host binding 8444 отсутствует | `tests/security_grade3.sh` |
| Broker/Collector mTLS identities | `make test-security-grade4` | no cert и same-CA intruder deny; broker принимает worker/dispatcher и запрещает API без broker edge; Collector принимает разные api/worker/dispatcher | `tests/security_grade4.sh`, `infrastructure/gateways/*.cfg` |
| TLS и ACL всей матрицы | `make test-acl-grade4`; grade3/4 security; policy tests | PostgreSQL verify-full; dispatcher recovery получает только нужные `SELECT,UPDATE` на attachments и не читает users/не удаляет attachments; остальные DB/Redis/Rabbit/S3/OpenBao allow/deny подтверждены | `tests/acl_audit_grade4.sh`, `contracts/trust-matrix.md` |
| OpenBao non-dev и least privilege | `make test-openbao-policy` | own path allow; worker path, policy admin и KV write deny | `tests/openbao_policy.sh`, `infrastructure/openbao/*` |
| Раздельные S3 права | `./tests/minio_policy.sh` | API staging write-only, attachments read-only; bucket create и anonymous GET deny | `infrastructure/minio/*-policy.template.json` |
| Argon2id floor и измерение | `make argon2-benchmark`; `go test ./internal/security` | `m=19456,t=2,p=1`, 23.485943 ms/op; слабая конфигурация отклоняется | `internal/security/password.go`, `password_test.go` |
| Rehash и login DoS budget | `go test ./student_tests ./internal/security`; `make login-dos-benchmark` | legacy `m=8192,t=1` обновлён после успешного login; verify 23.485943 ms/op; 5/60s ≈117 ms/identifier/min | `student_tests/password_rehash_test.go`, `password_test.go` |
| Общий login rate limit | `make test-rate-limit-grade3` | запросы прошли обе реплики; 5×401, затем 429 + Retry-After | `tests/rate_limit_grade3.py`, migration 000008 |
| Ограниченный cleanup auth state | `make test-state-pruning-grade4` | истёкшая limiter row удалена, активное окно с attempts=4 сохранено; batch/частота ограничены | `internal/adapter/postgres/maintenance.go`, `tests/state_pruning_grade4.sh` |
| Session expiry/logout, размер, ACL | `go test ./...`; `make test` | expired token и logout проверены; JSON/attachment reads ограничены; outsider/X-User-Id tests PASS | `student_tests/auth_test.go`, `internal/transport/http/handlers/handler.go` |
| Hardening, worker bounds и порты | `make test-security-grade4`; `tests/attachment_boundaries.py` | app rootfs read-only, no-new-privileges, CapDrop ALL; worker 1 CPU/512 MiB, concurrency 1, GOMEMLIMIT 448 MiB, timeout 60 s; ровно 40 Мп обработаны без OOM | `compose.yaml`, `tests/security_grade4.sh`, `tests/attachment_boundaries.py` |
| Secret/leaf rotation и revoke | `make rotate-secret-grade4`; `make rotate-leaf-grade4` | broker worker password заменён и старый отвергнут; новый LB leaf принят, старый URI и expired leaf отвергнут; image IDs неизменны | `scripts/rotate-*-grade4.sh` |
| OpenBao renewal/expiry/seal | `make test-openbao-lifecycle-grade4` | one-use SecretID reuse deny; token renewal работает после original TTL и прекращается на max TTL; running API жив при seal, fresh API fail-closed, unseal восстанавливает | `tests/openbao_lifecycle_grade4.sh` |
| Отсутствие credential telemetry | `make test-telemetry-leak-grade4` | Loki содержит structured events, но не login probe, Basic/Bearer, request body и значения ignored secret files | `tests/telemetry_leak_grade4.sh` |
| Перезапуск с данными и unseal | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | подтверждённые данные, attachment и существующая сессия сохранены | `scripts/restart.sh` |
| Одна API-реплика остановлена | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 2 instance до отказа; 110 успешных writes, 8 transient failures; восстановление 4.932 s; потерь/дублей нет | `scripts/stop-one.sh` |
| Dependency/image scan | `make scan-grade4` | `govulncheck`: no reachable vulnerabilities; strict Trivy: app/ingress 0 HIGH/CRITICAL fixed; vendor scan: MinIO 40 HIGH/4 CRITICAL, mc 26 HIGH/1 CRITICAL — архивированный upstream, применимость и production-блокер зафиксированы | `security/SCAN_TRIAGE.md`, `scripts/scan-grade4.sh` |
## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
Стенд: Intel Core i5-1135G7, 8 vCPU WSL, доступно 3.7 GiB RAM. Compose limits: каждая API 0.5 CPU/256 MiB, ingress 0.25 CPU/128 MiB, PostgreSQL 1 CPU/512 MiB. Нагрузка — closed-loop POST messages, 4 клиента, 30 s, без retry и без прогрева. Это измерение одного ноутбука, а не capacity/SLO proof.
- 1959 успешных, 0 ошибок, 65.095 successful RPS.
- p50 87.901 ms, p95 100.057 ms, p99 106.397 ms.
- Снимок во время нагрузки: API-1 10.19% CPU / 16.38 MiB; API-2 11.07% / 21.2 MiB; ingress 25.09% / 23.41 MiB; PostgreSQL 13.89% / 68.33 MiB.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
| Restart stateful stores с volumes, seal/unseal OpenBao, recreate app | API временно недоступен, затем старая session/data работают | persistence PASS, operator hook завершён < 90 s | потеря подтверждённых данных: 0 |
| Stop одной из двух API-реплик | HAProxy исключает реплику и продолжает через вторую | 110 writes успешны, 8 transient failures в окне обнаружения | 4.932 s до первого успеха; потерь/дублей: 0 |
| mTLS negative probes | handshake/authorization deny до business API | все negative cases отклонены, correct identities приняты | немедленно; данных не меняет |
Raw sanitized summaries находятся в `evidence/grade3-summary.md` и `evidence/grade4-summary.md`; session tokens и secret values туда не записаны.
## Финальный аудит bottleneck/error paths
- Максимальная разрешённая граница проверена реальной декодировкой PNG: 10 MiB и ровно 40 000 000 pixels прошли, immediately-after-test worker memory составила 426.3 MiB из 512 MiB, `OOMKilled=false`. Concurrency уменьшена с 2 до 1; это осознанно ограничивает throughput одного worker, но убирает риск двух одновременных полных декодировок в одном cgroup.
- Рост `sessions`, `message_idempotency` и `login_rate_limits` ограничен batch cleanup. Запросы используют существующие индексы, `LIMIT 256` и `FOR UPDATE SKIP LOCKED`; cleanup не выполняется на каждом запросе. Отдельный regression test защищает от преждевременного удаления активного rate-limit window.
- На реальном просроченном attachment job обнаружена и устранена permission loop: dispatcher требовался `UPDATE` для `SELECT ... FOR UPDATE` и смены статуса attachment. После точечного grant reaper восстановил job как следующую попытку; destructive/unrelated права остались запрещены.
- Две API-реплики и предыдущий 30-секундный closed-loop load не показали saturation приложения/БД; ingress был самым загруженным компонентом (25.09% выделенного CPU). Эти цифры не являются production capacity proof.
- Оставшиеся архитектурные bottlenecks осознанны для оценки 4: один worker, один dispatcher, один ingress и single-instance stateful services. Горизонтальный/host-level HA относится к следующему уровню и не заявлен.
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
Это single-host учебный стенд: отказ Docker host, единственных ingress/PostgreSQL/OpenBao/CA не переживается. Две API-реплики дают только process failover. HAProxy TLS proxy создаёт намеренный локальный plaintext hop к Redis/MinIO/RabbitMQ и telemetry backends; hop закрыт отдельной internal network, но не равен end-to-end TLS внутри продукта.
Статические DB/S3/Rabbit/Redis credentials требуют operator rotation; сценарий уровня 4 доказывает это для рабочего RabbitMQ secret, но автоматические dynamic database credentials не реализованы. AppRole SecretID имеет 7-дневный TTL и unlimited uses для штатных сервисов; отдельный lifecycle test доказывает one-use revoke. Leaf certificates действуют 365 дней, CA — 10 лет; отзыв leaf реализован exact identity allowlist, но автоматических CRL/OCSP и фонового renewal agent нет. Запущенные процессы продолжают работу при seal/OpenBao с уже загруженными credentials, новый процесс fail-closed не стартует до operator unseal.
Уровень 5 не заявлен: нет исследовательского compromise/PKI lifecycle track, автоматической CA rotation, multi-host HA и production KMS/HSM. Официальные MinIO/mc upstream архивированы; их известные vendor dependency findings приняты только для учебного стенда и являются production-блокером до замены storage/maintained fork. Image scan — снимок базы на дату проверки, а не гарантия отсутствия будущих CVE.
+169
View File
@@ -0,0 +1,169 @@
package main
import (
"context"
"errors"
"log"
"os"
"os/signal"
"syscall"
"time"
"mtusi2026lab7/internal/adapter/broker"
"mtusi2026lab7/internal/adapter/postgres"
"mtusi2026lab7/internal/config"
"mtusi2026lab7/internal/database"
"mtusi2026lab7/internal/domain"
appsecrets "mtusi2026lab7/internal/secrets"
apptelemetry "mtusi2026lab7/internal/telemetry"
"mtusi2026lab7/internal/worker"
)
const defaultBeforePublishFaultFile = "/tmp/mtusi-fault-before-publish"
func main() {
secretContext, secretCancel := context.WithTimeout(context.Background(), 15*time.Second)
err := appsecrets.LoadOpenBaoEnvironment(secretContext)
secretCancel()
if err != nil {
log.Fatalf("[FATAL] OpenBao secret bootstrap failed: %v", err)
}
cfg, err := config.LoadDispatcher()
if err != nil {
log.Fatalf("[FATAL] Invalid configuration: %v", err)
}
if cfg.BrokerURL == "" {
log.Fatal("[FATAL] BROKER_URL or BROKER_URL_FILE is required")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
telemetryRuntime, err := apptelemetry.Start(ctx, "messenger-dispatcher", cfg.InstanceID, "lab")
if err != nil {
log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err)
}
defer func() {
shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil {
log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr)
}
}()
pool, err := database.Open(ctx, cfg)
if err != nil {
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
}
defer pool.Close()
if err = apptelemetry.RegisterDBPool(telemetryRuntime, pool); err != nil {
log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err)
}
store := postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout)
queueRecorder, err := apptelemetry.NewQueueRecorder(telemetryRuntime)
if err != nil {
log.Fatalf("[FATAL] Queue observability initialization failed: %v", err)
}
client, err := broker.Open(cfg.BrokerURL, 0)
if err != nil {
log.Fatalf("[FATAL] RabbitMQ initialization failed: %v", err)
}
defer client.Close()
faultFile := os.Getenv("DISPATCHER_FAULT_BEFORE_PUBLISH_FILE")
if faultFile == "" {
faultFile = defaultBeforePublishFaultFile
}
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
log.Println("[INFO] Attachment job dispatcher and lease reaper started")
nextQueueObservation := time.Time{}
for {
now := time.Now().UTC()
if !now.Before(nextQueueObservation) {
depth, ageSeconds, statsErr := store.AttachmentQueueStats(ctx, now)
if statsErr != nil {
if ctx.Err() == nil {
log.Printf("[WARN] Read queue stats failed: %v", statsErr)
}
} else {
queueRecorder.Record(ctx, depth, ageSeconds)
}
nextQueueObservation = now.Add(time.Second)
}
expired, queryErr := store.ListExpiredAttachmentJobs(ctx, now, 50)
if queryErr != nil {
if ctx.Err() != nil {
return
}
log.Printf("[WARN] List expired jobs failed: %v", queryErr)
} else {
for _, job := range expired {
delay := worker.RetryDelay(
job.JobID,
job.Attempt+1,
cfg.JobRetryBase,
cfg.JobRetryMax,
)
recovered, final, recoverErr := store.RetryAttachmentJob(
ctx,
job.JobID,
"lease_expired",
now.Add(delay),
now,
"lease_recovered",
)
if recoverErr != nil {
log.Printf("[WARN] Recover expired job %s failed: %v", job.JobID, recoverErr)
continue
}
if final && recovered.Status == domain.AttachmentJobFailed {
log.Printf("[WARN] Expired job %s exhausted retries", job.JobID)
} else if !final {
log.Printf("[INFO] Recovered expired job %s as attempt %d", job.JobID, recovered.Attempt)
}
}
}
jobs, queryErr := store.ListUnpublishedAttachmentJobs(ctx, 50)
if queryErr != nil {
if ctx.Err() != nil {
return
}
log.Printf("[WARN] List unpublished jobs failed: %v", queryErr)
} else {
for _, job := range jobs {
removeErr := os.Remove(faultFile)
if removeErr == nil {
log.Printf("[FAULT] exiting after DB commit and before publish for job %s", job.JobID)
os.Exit(87)
}
if removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) {
log.Printf("[WARN] Consume before-publish fault marker: %v", removeErr)
}
publishContext, cancel := context.WithTimeout(ctx, 10*time.Second)
publishErr := client.Publish(publishContext, job)
cancel()
if publishErr != nil {
log.Fatalf("[FATAL] Publish job %s failed: %v", job.JobID, publishErr)
}
if err = store.MarkAttachmentJobPublished(
ctx,
job.JobID,
job.Attempt,
time.Now().UTC(),
); err != nil {
// Publisher confirm proves broker acceptance. Leaving the
// marker unset intentionally causes a safe duplicate.
log.Printf("[WARN] Job %s was confirmed but publish marker failed: %v", job.JobID, err)
}
}
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
+259
View File
@@ -0,0 +1,259 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strconv"
"time"
"mtusi2026lab7/internal/adapter/broker"
"mtusi2026lab7/internal/adapter/objectstore"
"mtusi2026lab7/internal/adapter/postgres"
"mtusi2026lab7/internal/application"
"mtusi2026lab7/internal/config"
"mtusi2026lab7/internal/database"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
)
type jobView struct {
JobID string `json:"job_id"`
AttachmentID string `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Status domain.AttachmentJobStatus `json:"status"`
Attempt int `json:"attempt"`
MaxAttempts int `json:"max_attempts"`
ErrorCode *string `json:"error_code"`
ReplayCount int `json:"replay_count"`
UpdatedAt time.Time `json:"updated_at"`
}
func main() {
if len(os.Args) < 2 {
usage()
}
switch os.Args[1] {
case "list-failed":
runListFailed()
case "replay":
runReplay()
case "inject":
runInject()
case "upgrade":
runUpgrade()
default:
usage()
}
}
func openStore(ctx context.Context, cfg config.Config) (*postgres.PostgreSQLStore, func()) {
pool, err := database.Open(ctx, cfg)
if err != nil {
log.Fatalf("PostgreSQL initialization failed: %v", err)
}
return postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout), pool.Close
}
func runListFailed() {
limit := 100
if len(os.Args) == 3 {
parsed, err := strconv.Atoi(os.Args[2])
if err != nil || parsed < 1 || parsed > 1000 {
log.Fatal("limit must be an integer between 1 and 1000")
}
limit = parsed
} else if len(os.Args) != 2 {
usage()
}
cfg, err := config.LoadDispatcher()
if err != nil {
log.Fatalf("invalid configuration: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
store, closeStore := openStore(ctx, cfg)
defer closeStore()
jobs, err := store.ListFailedAttachmentJobs(ctx, limit)
if err != nil {
log.Fatalf("list failed jobs: %v", err)
}
views := make([]jobView, 0, len(jobs))
for _, job := range jobs {
views = append(views, view(job))
}
writeJSON(views)
}
func runReplay() {
if len(os.Args) != 3 {
usage()
}
jobID := requireUUID(os.Args[2], "job_id")
cfg, err := config.LoadDispatcher()
if err != nil {
log.Fatalf("invalid configuration: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
store, closeStore := openStore(ctx, cfg)
defer closeStore()
job, err := store.ReplayFailedAttachmentJob(ctx, jobID, time.Now().UTC())
if errors.Is(err, postgres.ErrConflict) {
log.Fatal("replay rejected: job is not the active failed pipeline or retained staging is unavailable")
}
if errors.Is(err, postgres.ErrNotFound) {
log.Fatal("replay rejected: job not found")
}
if err != nil {
log.Fatalf("replay failed: %v", err)
}
writeJSON(view(job))
}
func runInject() {
if len(os.Args) != 3 {
usage()
}
jobID := requireUUID(os.Args[2], "job_id")
cfg, err := config.LoadDispatcher()
if err != nil {
log.Fatalf("invalid configuration: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
store, closeStore := openStore(ctx, cfg)
defer closeStore()
job, err := store.GetAttachmentJob(ctx, jobID)
if errors.Is(err, postgres.ErrNotFound) {
log.Fatal("inject rejected: job not found")
}
if err != nil {
log.Fatalf("read job for injection: %v", err)
}
client, err := broker.Open(cfg.BrokerURL, 1)
if err != nil {
log.Fatalf("RabbitMQ initialization failed: %v", err)
}
defer client.Close()
if err = client.Publish(ctx, job); err != nil {
log.Fatalf("inject broker message: %v", err)
}
writeJSON(view(job))
}
func runUpgrade() {
if len(os.Args) != 4 {
usage()
}
attachmentID := requireUUID(os.Args[2], "attachment_id")
targetVersion, err := strconv.Atoi(os.Args[3])
if err != nil || targetVersion != 2 {
log.Fatal("target pipeline version must be 2")
}
cfg, err := config.LoadWorker()
if err != nil {
log.Fatalf("invalid configuration: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
store, closeStore := openStore(ctx, cfg)
defer closeStore()
attachment, err := store.GetAttachmentForProcessing(ctx, attachmentID)
if errors.Is(err, postgres.ErrNotFound) {
log.Fatal("upgrade rejected: attachment not found")
}
if err != nil {
log.Fatalf("read attachment for upgrade: %v", err)
}
if attachment.PipelineVersion+1 != targetVersion {
log.Fatalf("upgrade rejected: current pipeline is v%d", attachment.PipelineVersion)
}
objects, err := objectstore.NewMinIOStore(
cfg.S3Endpoint,
cfg.S3Region,
cfg.S3Bucket,
cfg.S3AccessKeyID,
cfg.S3SecretAccessKey,
cfg.S3OperationTimeout,
)
if err != nil {
log.Fatalf("object storage initialization failed: %v", err)
}
source, err := objects.Get(ctx, attachment.ObjectKey)
if err != nil {
log.Fatalf("upgrade source original is unavailable: %v", err)
}
defer source.Body.Close()
stagingKey := fmt.Sprintf("staging/%s/v%d/original", attachment.ID, targetVersion)
if err = objects.Put(ctx, application.ObjectPut{
Key: stagingKey,
ContentType: attachment.ContentType,
SizeBytes: attachment.SizeBytes,
Body: source.Body,
}); err != nil {
log.Fatalf("create durable upgrade staging: %v", err)
}
now := time.Now().UTC()
job := domain.AttachmentJob{
SchemaVersion: 1,
JobID: uuid.NewString(),
Type: domain.AttachmentJobType,
AttachmentID: attachment.ID,
PipelineVersion: targetVersion,
Attempt: 1,
MaxAttempts: cfg.JobMaxAttempts,
Status: domain.AttachmentJobQueued,
AvailableAt: now,
CreatedAt: now,
UpdatedAt: now,
}
job, err = store.UpgradeAttachmentPipeline(ctx, attachment.ID, targetVersion, stagingKey, job, now)
if errors.Is(err, postgres.ErrConflict) {
log.Fatal("upgrade rejected: attachment is not in an upgradeable state or target is not the next version")
}
if err != nil {
// Keep the copied source: a COMMIT error is ambiguous and cleanup can
// safely remove an actual orphan after the retention period.
log.Fatalf("upgrade pipeline: %v", err)
}
writeJSON(view(job))
}
func requireUUID(value, name string) string {
if _, err := uuid.Parse(value); err != nil {
log.Fatalf("%s must be a UUID", name)
}
return value
}
func view(job domain.AttachmentJob) jobView {
return jobView{
JobID: job.JobID,
AttachmentID: job.AttachmentID,
PipelineVersion: job.PipelineVersion,
Status: job.Status,
Attempt: job.Attempt,
MaxAttempts: job.MaxAttempts,
ErrorCode: job.ErrorCode,
ReplayCount: job.ReplayCount,
UpdatedAt: job.UpdatedAt,
}
}
func writeJSON(value any) {
encoder := json.NewEncoder(os.Stdout)
encoder.SetEscapeHTML(true)
if err := encoder.Encode(value); err != nil {
log.Fatalf("encode output: %v", err)
}
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: jobctl list-failed [limit] | replay <job_id> | inject <job_id> | upgrade <attachment_id> 2")
os.Exit(2)
}
+75
View File
@@ -0,0 +1,75 @@
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"time"
"mtusi2026lab7/internal/adapter/objectstore"
"mtusi2026lab7/internal/adapter/postgres"
"mtusi2026lab7/internal/config"
"mtusi2026lab7/internal/database"
"mtusi2026lab7/internal/reconcile"
)
func main() {
apply := flag.Bool("apply", false, "apply safe repairs; default is dry-run")
gracePeriod := flag.Duration("grace-period", 15*time.Minute,
"ignore metadata and objects newer than this duration")
timeout := flag.Duration("timeout", 2*time.Minute, "maximum reconciliation runtime")
flag.Parse()
if *gracePeriod <= 0 || *timeout <= 0 {
log.Fatal("[FATAL] grace-period and timeout must be positive")
}
cfg, err := config.Load()
if err != nil {
log.Fatalf("[FATAL] Invalid configuration: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
defer cancel()
databasePool, err := database.Open(ctx, cfg)
if err != nil {
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
}
defer databasePool.Close()
metadataStore := postgres.NewPostgreSQLStore(databasePool, cfg.DatabaseQueryTimeout)
objectStore, err := objectstore.NewMinIOStore(
cfg.S3Endpoint,
cfg.S3Region,
cfg.S3Bucket,
cfg.S3AccessKeyID,
cfg.S3SecretAccessKey,
cfg.S3OperationTimeout,
)
if err != nil {
log.Fatalf("[FATAL] Invalid object storage configuration: %v", err)
}
if err = objectStore.Ping(ctx); err != nil {
log.Fatalf("[FATAL] Object storage unavailable: %v", err)
}
reconciler, err := reconcile.New(metadataStore, objectStore)
if err != nil {
log.Fatalf("[FATAL] Reconciler initialization failed: %v", err)
}
result, err := reconciler.Run(ctx, *gracePeriod, *apply)
if err != nil {
log.Fatalf("[FATAL] Reconciliation failed: %v", err)
}
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
if err = encoder.Encode(result); err != nil {
log.Fatalf("[FATAL] Encode reconciliation result: %v", err)
}
if !*apply && len(result.Issues) > 0 {
fmt.Fprintln(os.Stderr, "dry-run found reconciliation issues; rerun with --apply after review")
}
}
+310
View File
@@ -0,0 +1,310 @@
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
cacheadapter "mtusi2026lab7/internal/adapter/cache"
"mtusi2026lab7/internal/adapter/health"
"mtusi2026lab7/internal/adapter/objectstore"
"mtusi2026lab7/internal/adapter/postgres"
redisadapter "mtusi2026lab7/internal/adapter/redis"
"mtusi2026lab7/internal/application"
"mtusi2026lab7/internal/config"
"mtusi2026lab7/internal/database"
appsecrets "mtusi2026lab7/internal/secrets"
appsecurity "mtusi2026lab7/internal/security"
apptelemetry "mtusi2026lab7/internal/telemetry"
"mtusi2026lab7/internal/transport/http/handlers"
"mtusi2026lab7/internal/transport/http/middleware"
)
func main() {
secretContext, secretCancel := context.WithTimeout(context.Background(), 15*time.Second)
err := appsecrets.LoadOpenBaoEnvironment(secretContext)
secretCancel()
if err != nil {
log.Fatalf("[FATAL] OpenBao secret bootstrap failed: %v", err)
}
cfg, err := config.Load()
if err != nil {
log.Fatalf("[FATAL] Invalid configuration: %v", err)
}
if instanceIDFile := os.Getenv("INSTANCE_ID_FILE"); instanceIDFile != "" {
if err = os.WriteFile(instanceIDFile, []byte(cfg.InstanceID), 0o600); err != nil {
log.Fatalf("[FATAL] Persist runtime instance alias: %v", err)
}
}
telemetryRuntime, err := apptelemetry.Start(
context.Background(),
"messenger-api",
cfg.InstanceID,
"lab",
)
if err != nil {
log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err)
}
defer func() {
shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil {
log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr)
}
}()
startupContext, startupCancel := context.WithTimeout(
context.Background(),
cfg.DatabaseConnectTimeout,
)
databasePool, err := database.Open(startupContext, cfg)
startupCancel()
if err != nil {
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
}
defer databasePool.Close()
if err = apptelemetry.RegisterDBPool(telemetryRuntime, databasePool); err != nil {
log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err)
}
postgresStore := postgres.NewPostgreSQLStore(
databasePool,
cfg.DatabaseQueryTimeout,
)
minioStore, err := objectstore.NewMinIOStore(
cfg.S3Endpoint,
cfg.S3Region,
cfg.S3Bucket,
cfg.S3AccessKeyID,
cfg.S3SecretAccessKey,
cfg.S3OperationTimeout,
)
if err != nil {
log.Fatalf("[FATAL] Invalid object storage configuration: %v", err)
}
storageContext, storageCancel := context.WithTimeout(
context.Background(),
cfg.S3OperationTimeout,
)
if err = minioStore.Ping(storageContext); err != nil {
log.Printf("[WARN] Object storage unavailable at startup: %v", err)
}
storageCancel()
var applicationStore application.Repository = postgresStore
if cfg.RedisURL != "" {
redisChatCache, cacheError := redisadapter.NewRedisChatCache(
cfg.RedisURL,
cfg.RedisCacheTTL,
cfg.RedisOperationTimeout,
cfg.RedisPoolSize,
)
if cacheError != nil {
log.Fatalf("[FATAL] Invalid Redis configuration: %v", cacheError)
}
defer func() {
if closeError := redisChatCache.Close(); closeError != nil {
log.Printf("[WARN] Redis client close failed: %v", closeError)
}
}()
cacheContext, cacheCancel := context.WithTimeout(
context.Background(),
cfg.RedisOperationTimeout,
)
if cacheError = redisChatCache.Ping(cacheContext); cacheError != nil {
log.Printf("[WARN] Redis unavailable at startup; PostgreSQL fallback is active: %v", cacheError)
} else {
log.Println("[INFO] Redis chat cache is available")
}
cacheCancel()
applicationStore = cacheadapter.NewCachedRepository(
postgresStore,
redisChatCache,
log.Default(),
)
}
cursorCodec, err := application.NewCursorCodec(cfg.CursorSigningKey)
if err != nil {
log.Fatalf("[FATAL] Invalid cursor configuration: %v", err)
}
service, err := application.NewService(
applicationStore,
cursorCodec,
cfg.SessionTTL,
application.WithIdempotencyTTL(cfg.IdempotencyTTL),
application.WithObjectStore(minioStore),
application.WithJobMaxAttempts(cfg.JobMaxAttempts),
)
if err != nil {
log.Fatalf("[FATAL] Application initialization failed: %v", err)
}
handler := handlers.NewHandler(
service,
handlers.WithReadiness(
health.NewMultiChecker(databasePool, minioStore),
cfg.ReadinessTimeout,
),
handlers.WithSessionCookieSecure(cfg.SessionCookieSecure),
handlers.WithLoginRateLimit(postgresStore, cfg.LoginRateLimit, cfg.LoginRateWindow),
)
mux := http.NewServeMux()
mux.HandleFunc("GET /health/live", handler.HealthLive)
mux.HandleFunc("GET /health/lb", handler.HealthLive)
mux.HandleFunc("GET /health/ready", handler.HealthReady)
mux.HandleFunc(
"POST /api/v1/auth/sessions",
handler.CreateSession,
)
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
requireAuth := func(next http.HandlerFunc) http.HandlerFunc {
return middleware.RequireAuth(service, next)
}
mux.HandleFunc(
"GET /api/v1/users/me",
requireAuth(handler.GetMe),
)
mux.HandleFunc(
"DELETE /api/v1/auth/sessions/current",
requireAuth(handler.DeleteCurrentSession),
)
mux.HandleFunc(
"POST /api/v1/chats",
requireAuth(handler.CreateChat),
)
mux.HandleFunc(
"GET /api/v1/chats",
requireAuth(handler.ListChats),
)
mux.HandleFunc(
"GET /api/v1/chats/{chat_id}",
requireAuth(handler.GetChat),
)
mux.HandleFunc(
"POST /api/v1/chats/{chat_id}/messages",
requireAuth(handler.CreateMessage),
)
mux.HandleFunc(
"GET /api/v1/chats/{chat_id}/messages",
requireAuth(handler.GetMessages),
)
mux.HandleFunc(
"POST /api/v1/chats/{chat_id}/attachments",
requireAuth(handler.UploadAttachment),
)
mux.HandleFunc(
"GET /api/v1/attachments/{attachment_id}",
requireAuth(handler.GetAttachment),
)
mux.HandleFunc(
"GET /api/v1/attachments/{attachment_id}/content",
requireAuth(handler.DownloadAttachment),
)
var rootHandler http.Handler = mux
rootHandler = middleware.Recovery(rootHandler)
rootHandler, err = middleware.Observability(telemetryRuntime, rootHandler)
if err != nil {
log.Fatalf("[FATAL] HTTP observability initialization failed: %v", err)
}
availabilityGate := middleware.NewAvailabilityGate()
rootHandler = availabilityGate.Middleware(rootHandler)
rootHandler = middleware.RequestID(rootHandler)
rootHandler = middleware.InstanceID(cfg.InstanceID, rootHandler)
server := &http.Server{
Addr: cfg.HTTPAddress(),
Handler: rootHandler,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
server.TLSConfig, err = appsecurity.ServerMTLSConfig(
os.Getenv("TLS_CLIENT_CA_FILE"),
os.Getenv("TLS_ALLOWED_CLIENT_URI"),
os.Getenv("TLS_ALLOWED_CLIENT_URIS_FILE"),
)
if err != nil {
log.Fatalf("[FATAL] Invalid internal mTLS configuration: %v", err)
}
tlsCertificateFile := os.Getenv("TLS_CERT_FILE")
tlsKeyFile := os.Getenv("TLS_KEY_FILE")
if tlsCertificateFile == "" || tlsKeyFile == "" {
log.Fatal("[FATAL] TLS_CERT_FILE and TLS_KEY_FILE are required")
}
serverErrors := make(chan error, 1)
go func() {
log.Printf(
"[INFO] Server instance %s starting on %s",
cfg.InstanceID,
server.Addr,
)
serverErrors <- server.ListenAndServeTLS(tlsCertificateFile, tlsKeyFile)
}()
shutdownSignals := make(chan os.Signal, 1)
signal.Notify(
shutdownSignals,
os.Interrupt,
syscall.SIGTERM,
)
defer signal.Stop(shutdownSignals)
select {
case serverError := <-serverErrors:
if !errors.Is(serverError, http.ErrServerClosed) {
log.Fatalf("[FATAL] Server crashed: %v", serverError)
}
case signalValue := <-shutdownSignals:
log.Printf(
"[INFO] Signal %v received. Starting graceful shutdown...",
signalValue,
)
availabilityGate.BeginDrain()
log.Printf(
"[INFO] Readiness disabled; draining new traffic for %s",
cfg.ShutdownDrainDelay,
)
time.Sleep(cfg.ShutdownDrainDelay)
shutdownContext, shutdownCancel := context.WithTimeout(
context.Background(),
cfg.ShutdownTimeout,
)
defer shutdownCancel()
if err := server.Shutdown(shutdownContext); err != nil {
log.Printf(
"[WARN] Graceful shutdown failed: %v. Forcing close.",
err,
)
_ = server.Close()
}
log.Println("[INFO] Server stopped gracefully.")
}
}
+280
View File
@@ -0,0 +1,280 @@
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"sync"
"syscall"
"time"
"mtusi2026lab7/internal/adapter/broker"
"mtusi2026lab7/internal/adapter/objectstore"
"mtusi2026lab7/internal/adapter/postgres"
"mtusi2026lab7/internal/config"
"mtusi2026lab7/internal/database"
"mtusi2026lab7/internal/domain"
appsecrets "mtusi2026lab7/internal/secrets"
apptelemetry "mtusi2026lab7/internal/telemetry"
"mtusi2026lab7/internal/worker"
)
const (
defaultBeforeObjectsFaultFile = "/tmp/mtusi-fault-before-objects"
defaultAfterObjectsFaultFile = "/tmp/mtusi-fault-after-objects"
)
func main() {
secretContext, secretCancel := context.WithTimeout(context.Background(), 15*time.Second)
err := appsecrets.LoadOpenBaoEnvironment(secretContext)
secretCancel()
if err != nil {
log.Fatalf("[FATAL] OpenBao secret bootstrap failed: %v", err)
}
cfg, err := config.LoadWorker()
if err != nil {
log.Fatalf("[FATAL] Invalid configuration: %v", err)
}
if cfg.BrokerURL == "" {
log.Fatal("[FATAL] BROKER_URL or BROKER_URL_FILE is required")
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
telemetryRuntime, err := apptelemetry.Start(
ctx,
"messenger-worker",
cfg.InstanceID,
"lab",
)
if err != nil {
log.Fatalf("[FATAL] OpenTelemetry initialization failed: %v", err)
}
defer func() {
shutdownContext, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if shutdownErr := telemetryRuntime.Shutdown(shutdownContext); shutdownErr != nil {
log.Printf("[WARN] OpenTelemetry shutdown failed: %v", shutdownErr)
}
}()
jobRecorder, err := apptelemetry.NewJobRecorder(telemetryRuntime, cfg.WorkerConcurrency)
if err != nil {
log.Fatalf("[FATAL] Worker observability initialization failed: %v", err)
}
pool, err := database.Open(ctx, cfg)
if err != nil {
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
}
defer pool.Close()
if err = apptelemetry.RegisterDBPool(telemetryRuntime, pool); err != nil {
log.Fatalf("[FATAL] DB pool observability initialization failed: %v", err)
}
store := postgres.NewPostgreSQLStore(pool, cfg.DatabaseQueryTimeout)
objects, err := objectstore.NewMinIOStore(
cfg.S3Endpoint,
cfg.S3Region,
cfg.S3Bucket,
cfg.S3AccessKeyID,
cfg.S3SecretAccessKey,
cfg.S3OperationTimeout,
)
if err != nil {
log.Fatalf("[FATAL] Object storage initialization failed: %v", err)
}
beforeFaultFile := os.Getenv("WORKER_FAULT_BEFORE_OBJECTS_FILE")
if beforeFaultFile == "" {
beforeFaultFile = defaultBeforeObjectsFaultFile
}
afterFaultFile := os.Getenv("WORKER_FAULT_AFTER_OBJECTS_FILE")
if afterFaultFile == "" {
afterFaultFile = defaultAfterObjectsFaultFile
}
processor, err := worker.NewProcessor(store, objects, worker.ProcessorHooks{
BeforeObjects: func(job domain.AttachmentJob) error {
removeErr := os.Remove(beforeFaultFile)
if errors.Is(removeErr, os.ErrNotExist) {
return nil
}
if removeErr != nil {
return fmt.Errorf("consume before-objects fault marker: %w", removeErr)
}
log.Printf("[FAULT] exiting before object writes for job %s", job.JobID)
os.Exit(85)
return nil
},
AfterObjects: func(job domain.AttachmentJob) error {
removeErr := os.Remove(afterFaultFile)
if errors.Is(removeErr, os.ErrNotExist) {
return nil
}
if removeErr != nil {
return fmt.Errorf("consume after-objects fault marker: %w", removeErr)
}
log.Printf("[FAULT] exiting after object writes and before DB commit for job %s", job.JobID)
os.Exit(86)
return nil
},
})
if err != nil {
log.Fatalf("[FATAL] Worker processor initialization failed: %v", err)
}
cleaner, err := worker.NewStagingCleaner(store, objects, cfg.StagingRetention)
if err != nil {
log.Fatalf("[FATAL] Staging cleaner initialization failed: %v", err)
}
var maintenance sync.WaitGroup
maintenance.Add(1)
go func() {
defer maintenance.Done()
runCleanup := func() {
cleanupContext, cancel := context.WithTimeout(ctx, cfg.S3OperationTimeout+cfg.DatabaseQueryTimeout)
deleted, cleanupErr := cleaner.RunOnce(cleanupContext, time.Now().UTC())
cancel()
if cleanupErr != nil && ctx.Err() == nil {
log.Printf("[WARN] Staging cleanup failed: %v", cleanupErr)
} else if deleted > 0 {
log.Printf("[INFO] Staging cleanup removed %d object(s)", deleted)
}
}
runCleanup()
ticker := time.NewTicker(cfg.StagingCleanupInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
runCleanup()
}
}
}()
client, err := broker.Open(cfg.BrokerURL, cfg.WorkerConcurrency)
if err != nil {
log.Fatalf("[FATAL] RabbitMQ initialization failed: %v", err)
}
defer client.Close()
deliveries, err := client.Consume(cfg.InstanceID)
if err != nil {
log.Fatalf("[FATAL] RabbitMQ consume failed: %v", err)
}
var group sync.WaitGroup
for index := 0; index < cfg.WorkerConcurrency; index++ {
group.Add(1)
go func(workerIndex int) {
defer group.Done()
workerID := fmt.Sprintf("%s-%d", cfg.InstanceID, workerIndex)
for delivery := range deliveries {
deliveryContext := broker.ContextFromDelivery(ctx, delivery)
message, decodeErr := broker.Decode(delivery)
if decodeErr != nil {
log.Printf("[WARN] Reject invalid broker message: %v", decodeErr)
_ = delivery.Reject(false)
continue
}
now := time.Now().UTC()
job, claimed, claimErr := store.ClaimAttachmentJob(
deliveryContext,
message,
workerID,
now.Add(cfg.JobLease),
)
if errors.Is(claimErr, postgres.ErrNotFound) {
log.Printf("[INFO] Stale broker message for missing job %s acknowledged", message.JobID)
_ = delivery.Ack(false)
continue
}
if claimErr != nil {
log.Printf("[WARN] Claim job %s failed: %v", message.JobID, claimErr)
_ = delivery.Nack(false, true)
continue
}
if !claimed {
_ = delivery.Ack(false)
continue
}
jobContext, cancel := context.WithTimeout(deliveryContext, cfg.JobTimeout)
jobContext, observedAttempt := jobRecorder.Start(
jobContext,
domain.AttachmentJobType,
broker.QueueName,
job.Attempt,
job.CreatedAt,
)
processErr := processor.Process(jobContext, job)
observedAttempt.End(processErr)
cancel()
if processErr == nil {
_ = delivery.Ack(false)
continue
}
var permanent *worker.PermanentError
if errors.As(processErr, &permanent) {
if failErr := store.FailAttachmentJob(
ctx,
job.JobID,
permanent.Code,
time.Now().UTC(),
); failErr != nil {
log.Printf("[WARN] Persist permanent failure for job %s failed: %v", job.JobID, failErr)
_ = delivery.Nack(false, true)
} else {
log.Printf("[WARN] Job %s failed permanently with %s", job.JobID, permanent.Code)
_ = delivery.Ack(false)
}
continue
}
retryAt := time.Now().UTC()
delay := worker.RetryDelay(
job.JobID,
job.Attempt+1,
cfg.JobRetryBase,
cfg.JobRetryMax,
)
retried, final, retryErr := store.RetryAttachmentJob(
ctx,
job.JobID,
"processing_failed",
retryAt.Add(delay),
retryAt,
"retry_scheduled",
)
if retryErr != nil {
log.Printf("[WARN] Schedule retry for job %s failed: %v", job.JobID, retryErr)
_ = delivery.Nack(false, true)
continue
}
if final && retried.Status == domain.AttachmentJobFailed {
log.Printf("[WARN] Job %s exhausted retries", job.JobID)
} else if final && retried.Status == domain.AttachmentJobSucceeded {
log.Printf("[INFO] Duplicate delivery for completed job %s acknowledged", job.JobID)
} else if final && retried.Status == domain.AttachmentJobSuperseded {
log.Printf("[INFO] Stale pipeline job %s acknowledged as superseded", job.JobID)
} else {
log.Printf("[INFO] Job %s retry %d scheduled after %s", job.JobID, retried.Attempt, delay)
}
_ = delivery.Ack(false)
}
}(index)
}
log.Printf(
"[INFO] Attachment worker started with concurrency=%d prefetch=%d lease=%s",
cfg.WorkerConcurrency,
cfg.WorkerConcurrency,
cfg.JobLease,
)
<-ctx.Done()
_ = client.Close()
group.Wait()
maintenance.Wait()
log.Println("[INFO] Attachment worker stopped")
}
+630
View File
@@ -0,0 +1,630 @@
name: mtusi2026lab7
x-app-security: &app-security
read_only: true
security_opt: [no-new-privileges:true]
cap_drop: [ALL]
tmpfs:
- /tmp:rw,nosuid,nodev,noexec,size=64m
x-app-environment: &app-environment
APP_ENV: lab
SSL_CERT_FILE: /run/secrets/tls_ca
BAO_ADDR: https://openbao:8200
BAO_CACERT: /run/secrets/tls_ca
OTEL_EXPORTER_OTLP_ENDPOINT: https://telemetry-gateway:4318
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_EXPORTER_OTLP_TIMEOUT: "3000"
OTEL_TRACES_SAMPLER: parentbased_always_on
CLIENT_TLS_CA_FILE: /run/secrets/tls_ca
CLIENT_TLS_CERT_FILE: /run/secrets/client_cert
CLIENT_TLS_KEY_FILE: /run/secrets/client_key
BROKER_TLS_SERVER_NAME: dependency-gateway
OTEL_TLS_SERVER_NAME: telemetry-gateway
services:
ingress:
build:
context: .
dockerfile: infrastructure/haproxy/Dockerfile
image: mtusi2026lab7-ingress
ports:
- "127.0.0.1:${HTTPS_PORT:-8443}:8443"
secrets: [tls_ca, ingress_pem, lb_client_pem]
networks: [host_access, api_ingress]
depends_on:
api:
condition: service_started
healthcheck:
test: [CMD, haproxy, -c, -f, /usr/local/etc/haproxy/haproxy.cfg]
interval: 10s
timeout: 5s
retries: 10
restart: unless-stopped
read_only: true
security_opt: [no-new-privileges:true]
cap_drop: [ALL]
deploy:
resources:
limits: {cpus: "0.25", memory: 128M}
api:
build:
context: .
dockerfile: Dockerfile
image: mtusi2026lab7-app
environment:
<<: *app-environment
APP_HOST: 0.0.0.0
APP_PORT: "8444"
INSTANCE_ID_FILE: /tmp/instance-id
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
SESSION_COOKIE_SECURE: "true"
IDEMPOTENCY_TTL_SECONDS: "86400"
LOGIN_RATE_LIMIT: ${LOGIN_RATE_LIMIT:-5}
LOGIN_RATE_WINDOW_SECONDS: ${LOGIN_RATE_WINDOW_SECONDS:-60}
ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456}
ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2}
ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1}
S3_ENDPOINT: https://dependency-gateway:9000
S3_REGION: us-east-1
S3_BUCKET: messenger-attachments
JOB_MAX_ATTEMPTS: "5"
TLS_CERT_FILE: /run/secrets/api_cert
TLS_KEY_FILE: /run/secrets/api_key
TLS_CLIENT_CA_FILE: /run/secrets/tls_ca
TLS_ALLOWED_CLIENT_URIS_FILE: /run/secrets/api_client_uris
BAO_ROLE_ID_FILE: /run/secrets/bao_role_id
BAO_SECRET_ID_FILE: /run/secrets/bao_secret_id
BAO_SECRET_PATH: api
BAO_ENV_KEYS: DATABASE_URL,CACHE_URL,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY,CURSOR_SIGNING_KEY
secrets:
- tls_ca
- api_cert
- api_key
- api_client_uris
- source: api_client_cert
target: client_cert
- source: api_client_key
target: client_key
- source: bao_api_role_id
target: bao_role_id
- source: bao_api_secret_id
target: bao_secret_id
networks: [api_ingress, postgres_network, dependency_secure, telemetry_secure, openbao_network]
expose: ["8444"]
depends_on:
postgres: {condition: service_healthy}
dependency-gateway: {condition: service_healthy}
telemetry-gateway: {condition: service_healthy}
openbao: {condition: service_healthy}
healthcheck:
disable: true
restart: unless-stopped
<<: *app-security
deploy:
replicas: ${API_REPLICAS:-2}
resources:
limits: {cpus: "0.50", memory: 256M}
postgres:
image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea
entrypoint: [/bin/sh, -ec]
command:
- |
install -d -o postgres -g postgres -m 700 /var/lib/postgresql/tls
install -o postgres -g postgres -m 600 /run/secrets/postgres_key /var/lib/postgresql/tls/server.key
install -o postgres -g postgres -m 644 /run/secrets/postgres_cert /var/lib/postgresql/tls/server.crt
install -o postgres -g postgres -m 644 /run/secrets/tls_ca /var/lib/postgresql/tls/ca.crt
exec docker-entrypoint.sh postgres \
-c ssl=on \
-c ssl_cert_file=/var/lib/postgresql/tls/server.crt \
-c ssl_key_file=/var/lib/postgresql/tls/server.key \
-c ssl_ca_file=/var/lib/postgresql/tls/ca.crt
environment:
POSTGRES_USER: lab7_admin
POSTGRES_DB: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_admin_password
secrets:
- postgres_admin_password
- postgres_api_password
- postgres_worker_password
- postgres_dispatcher_password
- postgres_cert
- postgres_key
- tls_ca
- postgres_roles
volumes: [postgres_data:/var/lib/postgresql/data]
networks: [postgres_network]
healthcheck:
test: [CMD-SHELL, pg_isready -U lab7_admin -d messenger]
interval: 5s
timeout: 3s
retries: 20
restart: unless-stopped
deploy:
resources:
limits: {cpus: "1.00", memory: 512M}
migrate:
image: migrate/migrate:v4.20.1@sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7
entrypoint: [/bin/sh, -ec]
command:
- |
password=$$(cat /run/secrets/postgres_admin_password)
exec migrate -path=/migrations \
-database="postgres://lab7_admin:$${password}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/tls_ca" up
secrets: [postgres_admin_password, tls_ca]
volumes:
- ./migrations:/migrations:ro
networks: [postgres_network]
depends_on:
postgres: {condition: service_healthy}
restart: "no"
deploy:
resources:
limits: {cpus: "0.25", memory: 64M}
redis:
image: redis:8.10.2-alpine3.23@sha256:3811787313eba226a2ef38658c6ccb91cd5e110edc89c37767de373120a0e5a0
command: [redis-server, /run/secrets/redis_config]
user: "1000:1000"
secrets:
- redis_config
- redis_api_password
networks: [redis_local]
healthcheck:
test: [CMD-SHELL, 'redis-cli -u "redis://api:$$(cat /run/secrets/redis_api_password)@127.0.0.1:6379/0" ping | grep -q PONG']
interval: 5s
timeout: 3s
retries: 20
restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.25", memory: 128M}
minio:
build:
context: .
dockerfile: infrastructure/minio/Dockerfile
target: server
args: {MINIO_VERSION: RELEASE.2025-10-15T17-29-55Z}
image: mtusi2026lab7-minio:RELEASE.2025-10-15T17-29-55Z
command: [server, /data, --address, ":9000"]
environment:
MINIO_ROOT_USER_FILE: /run/secrets/minio_root_user
MINIO_ROOT_PASSWORD_FILE: /run/secrets/minio_root_password
MINIO_BROWSER: "off"
secrets: [minio_root_user, minio_root_password]
volumes: [minio_data:/data]
networks: [s3_local]
healthcheck:
test: [CMD-SHELL, wget -qO- http://127.0.0.1:9000/minio/health/live >/dev/null]
interval: 5s
timeout: 3s
retries: 30
restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.75", memory: 512M}
minio-bootstrap:
build:
context: .
dockerfile: infrastructure/minio/Dockerfile
target: client
args: {MC_VERSION: RELEASE.2025-08-13T08-35-41Z}
image: mtusi2026lab7-mc:RELEASE.2025-08-13T08-35-41Z
entrypoint: [/bin/sh, -ec]
command:
- |
mc alias set local http://minio:9000 "$$(cat /run/secrets/minio_root_user)" "$$(cat /run/secrets/minio_root_password)" --api S3v4
mc mb --ignore-existing local/messenger-attachments
mc anonymous set none local/messenger-attachments
sed 's/__BUCKET__/messenger-attachments/g' /policies/api.json > /tmp/api.json
sed 's/__BUCKET__/messenger-attachments/g' /policies/worker.json > /tmp/worker.json
mc admin policy create local messenger-api /tmp/api.json
mc admin policy create local messenger-worker /tmp/worker.json
mc admin user add local "$$(cat /run/secrets/s3_api_access_key)" "$$(cat /run/secrets/s3_api_secret_key)"
mc admin user add local "$$(cat /run/secrets/s3_worker_access_key)" "$$(cat /run/secrets/s3_worker_secret_key)"
mc admin policy attach local messenger-api --user "$$(cat /run/secrets/s3_api_access_key)"
mc admin policy attach local messenger-worker --user "$$(cat /run/secrets/s3_worker_access_key)"
secrets:
- minio_root_user
- minio_root_password
- s3_api_access_key
- s3_api_secret_key
- s3_worker_access_key
- s3_worker_secret_key
volumes:
- ./infrastructure/minio/api-policy.template.json:/policies/api.json:ro
- ./infrastructure/minio/worker-policy.template.json:/policies/worker.json:ro
networks: [s3_local]
depends_on:
minio: {condition: service_healthy}
restart: "no"
broker:
image: rabbitmq:4.1.4-alpine
hostname: broker
entrypoint: [/bin/sh, -ec]
command:
- |
export RABBITMQ_DEFAULT_USER=dispatcher
export RABBITMQ_DEFAULT_PASS=$$(cat /run/secrets/broker_dispatcher_password)
exec docker-entrypoint.sh rabbitmq-server
secrets: [broker_dispatcher_password, broker_worker_password]
volumes: [broker_data:/var/lib/rabbitmq]
networks: [broker_local]
healthcheck:
test: [CMD, rabbitmq-diagnostics, -q, ping]
interval: 5s
timeout: 5s
retries: 30
restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.50", memory: 384M}
dependency-gateway:
image: haproxy:3.2-alpine@sha256:dfba86f031bd4c9039f10f8cc5de75991d1b6766d5460f0335b980408503baad
user: "1000:1000"
volumes:
- ./infrastructure/gateways/dependency.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
secrets: [dependency_pem, tls_ca]
networks: [dependency_secure, redis_local, s3_local, broker_local]
depends_on:
redis: {condition: service_healthy}
minio: {condition: service_healthy}
broker: {condition: service_healthy}
healthcheck:
test: [CMD, haproxy, -c, -f, /usr/local/etc/haproxy/haproxy.cfg]
interval: 10s
timeout: 5s
retries: 10
cap_drop: [ALL]
read_only: true
security_opt: [no-new-privileges:true]
restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.25", memory: 128M}
openbao:
image: openbao/openbao:2.4.4
user: "1000:1000"
command: [server, -config=/openbao/config/config.hcl]
environment:
BAO_ADDR: https://openbao:8200
BAO_CACERT: /run/secrets/tls_ca
secrets: [tls_ca, openbao_cert, openbao_key]
volumes:
- ./volumes/openbao:/openbao/data
- ./infrastructure/openbao/config.hcl:/openbao/config/config.hcl:ro
- ./infrastructure/openbao/api-policy.hcl:/policies/api-policy.hcl:ro
- ./infrastructure/openbao/worker-policy.hcl:/policies/worker-policy.hcl:ro
- ./infrastructure/openbao/dispatcher-policy.hcl:/policies/dispatcher-policy.hcl:ro
- ./secrets/openbao:/bootstrap:ro
networks: [host_access, openbao_network]
ports:
- "127.0.0.1:${OPENBAO_PORT:-18200}:8200"
healthcheck:
test: [CMD-SHELL, 'bao status >/dev/null 2>&1; code=$$?; [ $$code -eq 0 ] || [ $$code -eq 2 ]']
interval: 5s
timeout: 3s
retries: 30
restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.50", memory: 256M}
dispatcher:
build: {context: ., dockerfile: Dockerfile}
image: mtusi2026lab7-app
entrypoint: [/app/dispatcher]
environment:
<<: *app-environment
INSTANCE_ID: dispatcher
BAO_ROLE_ID_FILE: /run/secrets/bao_role_id
BAO_SECRET_ID_FILE: /run/secrets/bao_secret_id
BAO_SECRET_PATH: dispatcher
BAO_ENV_KEYS: DATABASE_URL,BROKER_URL
secrets:
- tls_ca
- source: dispatcher_client_cert
target: client_cert
- source: dispatcher_client_key
target: client_key
- source: bao_dispatcher_role_id
target: bao_role_id
- source: bao_dispatcher_secret_id
target: bao_secret_id
networks: [postgres_network, dependency_secure, telemetry_secure, openbao_network]
depends_on:
postgres: {condition: service_healthy}
dependency-gateway: {condition: service_healthy}
telemetry-gateway: {condition: service_healthy}
openbao: {condition: service_healthy}
restart: unless-stopped
<<: *app-security
deploy:
resources:
limits: {cpus: "0.25", memory: 128M}
worker:
build: {context: ., dockerfile: Dockerfile}
image: mtusi2026lab7-app
entrypoint: [/app/worker]
environment:
<<: *app-environment
INSTANCE_ID: worker
S3_ENDPOINT: https://dependency-gateway:9000
S3_REGION: us-east-1
S3_BUCKET: messenger-attachments
WORKER_CONCURRENCY: "1"
JOB_MAX_ATTEMPTS: "5"
JOB_TIMEOUT_SECONDS: "60"
JOB_LEASE_SECONDS: "75"
STAGING_RETENTION_SECONDS: "86400"
BAO_ROLE_ID_FILE: /run/secrets/bao_role_id
BAO_SECRET_ID_FILE: /run/secrets/bao_secret_id
BAO_SECRET_PATH: worker
BAO_ENV_KEYS: DATABASE_URL,BROKER_URL,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY
GOMEMLIMIT: 448MiB
secrets:
- tls_ca
- source: worker_client_cert
target: client_cert
- source: worker_client_key
target: client_key
- source: bao_worker_role_id
target: bao_role_id
- source: bao_worker_secret_id
target: bao_secret_id
networks: [postgres_network, dependency_secure, telemetry_secure, openbao_network]
depends_on:
postgres: {condition: service_healthy}
dependency-gateway: {condition: service_healthy}
telemetry-gateway: {condition: service_healthy}
openbao: {condition: service_healthy}
restart: unless-stopped
<<: *app-security
deploy:
resources:
limits: {cpus: "1.00", memory: 512M}
otel-collector:
image: otel/opentelemetry-collector-contrib:0.165.0
command: [--config=/etc/otelcol-contrib/config.yaml]
volumes:
- ./infrastructure/telemetry/otel-collector/config.yaml:/etc/otelcol-contrib/config.yaml:ro
secrets: [tls_ca, collector_client_cert, collector_client_key]
group_add: ["1000"]
networks: [collector_local, telemetry_secure]
depends_on:
loki: {condition: service_started}
tempo: {condition: service_started}
restart: unless-stopped
read_only: true
security_opt: [no-new-privileges:true]
cap_drop: [ALL]
tmpfs: ["/tmp:rw,nosuid,nodev,noexec,size=32m"]
deploy:
resources:
limits: {cpus: "0.50", memory: 256M}
loki:
image: grafana/loki:3.7.9
command: [-config.file=/etc/loki/config.yaml]
volumes:
- ./infrastructure/telemetry/loki/config.yaml:/etc/loki/config.yaml:ro
- loki_data:/loki
networks: [loki_local]
restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.50", memory: 384M}
tempo:
image: grafana/tempo:2.10.5
command: [-config.file=/etc/tempo/config.yaml]
volumes:
- ./infrastructure/telemetry/tempo/config.yaml:/etc/tempo/config.yaml:ro
- tempo_data:/var/tempo
networks: [tempo_local]
restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.50", memory: 384M}
prometheus:
image: prom/prometheus:v3.16.0
command:
- --config.file=/etc/prometheus/prometheus.yaml
- --storage.tsdb.path=/prometheus
- --storage.tsdb.retention.time=7d
volumes:
- ./infrastructure/telemetry/prometheus/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro
- ./infrastructure/telemetry/prometheus/rules:/etc/prometheus/rules:ro
- prometheus_data:/prometheus
secrets: [tls_ca, prometheus_client_cert, prometheus_client_key]
group_add: ["1000"]
networks: [prometheus_local, telemetry_secure]
depends_on:
telemetry-gateway: {condition: service_started}
restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.50", memory: 384M}
grafana:
image: grafana/grafana:13.3.0
user: "0:0"
environment:
GF_AUTH_ANONYMOUS_ENABLED: "false"
GF_SECURITY_ADMIN_USER: lab7-admin
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password
GF_ANALYTICS_REPORTING_ENABLED: "false"
GF_ANALYTICS_CHECK_FOR_UPDATES: "false"
SSL_CERT_FILE: /run/secrets/tls_ca
secrets: [tls_ca, grafana_admin_password]
volumes:
- grafana_data:/var/lib/grafana
- ./infrastructure/telemetry/grafana/provisioning:/etc/grafana/provisioning:ro
- ./secrets/grafana-datasources.yaml:/etc/grafana/provisioning/datasources/datasources.yaml:ro
- ./infrastructure/telemetry/grafana/dashboards:/var/lib/grafana/dashboards:ro
networks: [grafana_local, telemetry_secure]
depends_on:
prometheus: {condition: service_started}
loki: {condition: service_started}
tempo: {condition: service_started}
restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.50", memory: 384M}
telemetry-gateway:
image: haproxy:3.2-alpine@sha256:dfba86f031bd4c9039f10f8cc5de75991d1b6766d5460f0335b980408503baad
user: "1000:1000"
volumes:
- ./infrastructure/gateways/telemetry.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
secrets: [telemetry_pem, tls_ca]
networks: [host_access, telemetry_secure, collector_local, loki_local, tempo_local, prometheus_local, grafana_local]
ports:
- "127.0.0.1:${GRAFANA_PORT:-13000}:3000"
- "127.0.0.1:${PROMETHEUS_PORT:-19090}:9090"
- "127.0.0.1:${LOKI_PORT:-13100}:3100"
- "127.0.0.1:${TEMPO_PORT:-13200}:3200"
healthcheck:
test: [CMD, haproxy, -c, -f, /usr/local/etc/haproxy/haproxy.cfg]
interval: 10s
timeout: 5s
retries: 10
cap_drop: [ALL]
read_only: true
security_opt: [no-new-privileges:true]
restart: unless-stopped
deploy:
resources:
limits: {cpus: "0.25", memory: 128M}
security-test:
profiles: [tests]
build: {context: ., dockerfile: Dockerfile}
image: mtusi2026lab7-app
entrypoint: [curl]
secrets:
- source: tls_ca
target: ca.crt
- source: lb_client_cert
target: lb-client.crt
- source: lb_client_key
target: lb-client.key
- source: wrong_client_cert
target: wrong-client.crt
- source: wrong_client_key
target: wrong-client.key
- source: foreign_client_cert
target: foreign-client.crt
- source: foreign_client_key
target: foreign-client.key
- source: api_client_cert
target: api-client.crt
- source: api_client_key
target: api-client.key
- source: worker_client_cert
target: worker-client.crt
- source: worker_client_key
target: worker-client.key
- source: dispatcher_client_cert
target: dispatcher-client.crt
- source: dispatcher_client_key
target: dispatcher-client.key
networks: [api_ingress, dependency_secure, telemetry_secure]
cap_drop: [ALL]
read_only: true
security_opt: [no-new-privileges:true]
tmpfs: ["/tmp:rw,nosuid,nodev,noexec,size=16m"]
deploy:
resources:
limits: {cpus: "0.10", memory: 64M}
networks:
# A non-internal bridge is required for Docker to publish the explicitly
# loopback-bound operator ports. Application/dependency traffic stays on
# the isolated internal networks below.
host_access: {}
api_ingress: {internal: true}
postgres_network: {internal: true}
dependency_secure: {internal: true}
redis_local: {internal: true}
s3_local: {internal: true}
broker_local: {internal: true}
openbao_network: {internal: true}
telemetry_secure: {internal: true}
collector_local: {internal: true}
loki_local: {internal: true}
tempo_local: {internal: true}
prometheus_local: {internal: true}
grafana_local: {internal: true}
volumes:
postgres_data:
minio_data:
broker_data:
prometheus_data:
loki_data:
tempo_data:
grafana_data:
secrets:
tls_ca: {file: ./secrets/pki/ca.crt}
ingress_pem: {file: ./secrets/pki/ingress.pem}
api_cert: {file: ./secrets/pki/api.crt}
api_key: {file: ./secrets/pki/api.key}
api_client_uris: {file: ./secrets/pki/api-client-uris.txt}
api_client_cert: {file: ./secrets/pki/api-client.crt}
api_client_key: {file: ./secrets/pki/api-client.key}
worker_client_cert: {file: ./secrets/pki/worker-client.crt}
worker_client_key: {file: ./secrets/pki/worker-client.key}
dispatcher_client_cert: {file: ./secrets/pki/dispatcher-client.crt}
dispatcher_client_key: {file: ./secrets/pki/dispatcher-client.key}
lb_client_pem: {file: ./secrets/pki/lb-client.pem}
lb_client_cert: {file: ./secrets/pki/lb-client.crt}
lb_client_key: {file: ./secrets/pki/lb-client.key}
wrong_client_cert: {file: ./secrets/pki/wrong-client.crt}
wrong_client_key: {file: ./secrets/pki/wrong-client.key}
foreign_client_cert: {file: ./secrets/pki/foreign-client.crt}
foreign_client_key: {file: ./secrets/pki/foreign-client.key}
dependency_pem: {file: ./secrets/pki/dependency-gateway.pem}
telemetry_pem: {file: ./secrets/pki/telemetry-gateway.pem}
postgres_cert: {file: ./secrets/pki/postgres.crt}
postgres_key: {file: ./secrets/pki/postgres.key}
openbao_cert: {file: ./secrets/pki/openbao.crt}
openbao_key: {file: ./secrets/pki/openbao.key}
collector_client_cert: {file: ./secrets/pki/collector-client.crt}
collector_client_key: {file: ./secrets/pki/collector-client.key}
prometheus_client_cert: {file: ./secrets/pki/prometheus-client.crt}
prometheus_client_key: {file: ./secrets/pki/prometheus-client.key}
postgres_admin_password: {file: ./secrets/postgres_admin_password.txt}
postgres_api_password: {file: ./secrets/postgres_api_password.txt}
postgres_worker_password: {file: ./secrets/postgres_worker_password.txt}
postgres_dispatcher_password: {file: ./secrets/postgres_dispatcher_password.txt}
postgres_roles: {file: ./secrets/postgres-roles.sql}
redis_config: {file: ./secrets/redis.conf}
redis_api_password: {file: ./secrets/redis_api_password.txt}
minio_root_user: {file: ./secrets/minio_root_user.txt}
minio_root_password: {file: ./secrets/minio_root_password.txt}
s3_api_access_key: {file: ./secrets/s3_api_access_key.txt}
s3_api_secret_key: {file: ./secrets/s3_api_secret_key.txt}
s3_worker_access_key: {file: ./secrets/s3_worker_access_key.txt}
s3_worker_secret_key: {file: ./secrets/s3_worker_secret_key.txt}
broker_dispatcher_password: {file: ./secrets/broker_dispatcher_password.txt}
broker_worker_password: {file: ./secrets/broker_worker_password.txt}
grafana_admin_password: {file: ./secrets/grafana_admin_password.txt}
bao_api_role_id: {file: ./secrets/openbao/api_role_id.txt}
bao_api_secret_id: {file: ./secrets/openbao/api_secret_id.txt}
bao_worker_role_id: {file: ./secrets/openbao/worker_role_id.txt}
bao_worker_secret_id: {file: ./secrets/openbao/worker_secret_id.txt}
bao_dispatcher_role_id: {file: ./secrets/openbao/dispatcher_role_id.txt}
bao_dispatcher_secret_id: {file: ./secrets/openbao/dispatcher_secret_id.txt}
+28 -27
View File
@@ -1,37 +1,38 @@
# Матрица доверия — заполнить в решении lab7
# Матрица доверия — lab7, уровень 4
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
Локальный root CA создаётся `scripts/init-secrets.sh`: CA действует 3650 дней, leaf certificates — 365 дней. Private keys находятся только в ignored `secrets/pki` с mode 0600/0640; CA certificate может передаваться клиенту. TLS gateways допускают plaintext только на отдельной `internal: true` сети между gateway и одним backend без опубликованного обхода.
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
| --- | --- | --- | --- |
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
| Связь | Порт/endpoint и server trust | Client/service identity и права | Срок credential | Положительный/отрицательный тест и конфиг |
| --- | --- | --- | --- | --- |
| Клиент → ingress/LB | `127.0.0.1:8443`, TLS 1.3; local CA; SAN `DNS:localhost, IP:127.0.0.1` | Bearer session; Basic только `POST /auth/sessions`; session в общей PostgreSQL | session 3600 s; leaf 365 d | `make test-security`: CA pass, empty trust store certificate error. `make test`: outsider/X-User-Id/logout. `infrastructure/haproxy/haproxy.cfg` |
| LB → API (обе реплики) | `api:8444`, TLS 1.3; ingress проверяет local CA и `verifyhost api` | mTLS cert с версионируемой URI SAN; API требует CA и точную URI allowlist из runtime secret | leaf 365 d; operator rotation | `make test-security-grade3`; `make rotate-leaf-grade4`: no/foreign/wrong/old/expired deny, active LB allow, host binding отсутствует. `internal/security/mtls.go` |
| API/worker/dispatcher → PostgreSQL | `postgres:5432`, native TLS, `sslmode=verify-full`, local CA, SAN `postgres` | Отдельные `messenger_api`, `messenger_worker`, `messenger_dispatcher`; явные table/sequence GRANT, без admin | static lab password до operator rotation; получается через AppRole token 15m | `scripts/bootstrap-dependencies.sh`; `secrets/postgres-roles.sql` генерируется локально; `compose.yaml` не передаёт admin secret приложению |
| API/worker → S3 | `dependency-gateway:9000`, TLS 1.3, CA + SAN gateway; дальше только закрытая `s3_local` сеть к MinIO 9000 | API: Put `staging/*`, Get `attachments/*`; worker: Get/Delete staging, CRUD attachments; разные access keys | static lab key до operator rotation; выдаётся через scoped OpenBao path | `./tests/minio_policy.sh`: staging read deny, attachment write deny, bucket create/anonymous GET deny. `infrastructure/minio/*-policy.template.json` |
| Dispatcher/worker → broker | `dependency-gateway:5671`, TLS 1.3, CA + SAN gateway; локальный hop к RabbitMQ 5672 только `broker_local` | mTLS exact CN `dispatcher`/`worker` с разными URI SAN; затем `dispatcher` publish-only и `worker` consume-only Rabbit ACL. API cert намеренно deny: API пишет transactional outbox, а не broker | leaf 365 d; password operator-rotated через scoped KV | `make test-security-grade4`: no cert, same-CA intruder/API deny; worker/dispatcher allow. `make test-acl-grade4`; `make rotate-secret-grade4` old password deny |
| API/worker/dispatcher → Collector | `telemetry-gateway:4318`, TLS 1.3, CA + SAN `telemetry-gateway`; локальный hop только `collector_local` | mTLS exact CN ACL; отдельные `api`, `worker`, `dispatcher` clientAuth leaf/URI identities; ingest port не published; headers/body не экспортируются | leaf 365 d | `make test-security-grade4`: no cert и same-CA intruder deny; все три scoped identities allow. `make test-telemetry-leak-grade4` |
| Collector → telemetry backends | HTTPS gateway `3100` (Loki), `4319` (Tempo); CA + SAN gateway | mTLS CN `otel-collector`, URI `spiffe://mtusi/lab7/collector`; Loki допускает collector write/Grafana read, Tempo ingest — только collector | leaf 365 d | HAProxy `verify required` + exact CN ACL. Missing/other client cert rejected; live Collector reports `Everything is ready` |
| Prometheus → Collector metrics | HTTPS gateway `8888/8889`; CA + SAN gateway | mTLS CN `prometheus`, URI `spiffe://mtusi/lab7/prometheus`; эти ports допускают только Prometheus | leaf 365 d | `prometheus.yaml` cert/key; targets scrape через `telemetry-gateway`; no-cert gateway connection rejected |
| Grafana → data sources | HTTPS gateway `9090/3100/3200`; CA + SAN gateway | mTLS CN `grafana`, URI `spiffe://mtusi/lab7/grafana`; generated ignored datasource provisioning embeds local client key, backend ACL разрешает только Grafana (Loki также collector) | leaf 365 d; Grafana admin password static local | `make test-security-grade3`: no cert и LB cert deny, Grafana cert allow на Prometheus. `secrets/grafana-datasources.yaml` не в Git |
| API/worker/dispatcher → OpenBao | `openbao:8200`, native TLS 1.3, CA + SAN `openbao` | AppRole `api`, `worker`, `dispatcher`; каждая policy — read только `secret/data/<role>`; root/unseal отсутствуют в app | token TTL 15m/max 30m; SecretID 168h; lifecycle test uses bounded 10s/24s token and one-use SecretID | policy allow/deny plus `make test-openbao-lifecycle-grade4`: reuse/expiry/seal/fresh-start fail-closed/unseal recovery |
| Оператор → OpenBao/Grafana/S3 admin | OpenBao `127.0.0.1:18200` TLS; Grafana `127.0.0.1:13000` TLS; S3 admin port не published | OpenBao root/unseal только `.operator` 0600; Grafana login password file; MinIO root только one-shot bootstrap service | operator material до ручной rotation; Grafana/MinIO static local | `docker compose ps` показывает loopback binding; API containers не имеют MinIO root/OpenBao root. `./tests/minio_policy.sh` |
| API → Redis | `dependency-gateway:6380`, TLS 1.3, CA + SAN gateway; локальный hop только `redis_local` | Redis ACL user `api`: `~chat:v2:*`, команды get/set/del/ping; default user off | static lab password до operator rotation; scoped API OpenBao path | generated ignored `secrets/redis.conf`; Redis 6379 не published; readiness/cache tests проходят |
| Replication/cluster channels | N/A: PostgreSQL, Redis, MinIO, RabbitMQ, OpenBao и telemetry stores одноузловые | Кластерная/host HA не заявлена; две API-реплики разделяют stores | N/A | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` доказывает только API process failover, не отказ host/store |
## Обязательные отрицательные проверки
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех.
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity.
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
1. `make test-security` различает успешный HTTPS и ошибку certificate verification с пустым trust store.
2. `make test-security-grade3` выполняет четыре LB→API случая и проверяет отсутствие host binding API. Тем же скриптом telemetry backend отвергает отсутствие cert и доверенный LB cert, но принимает Grafana identity.
3. `make test` проверяет, что пользователь вне чата не читает metadata/content, а `X-User-Id` не переопределяет Bearer identity.
4. `make test-openbao-policy` доказывает allow/deny scoped AppRole без передачи root token приложению.
5. `./tests/minio_policy.sh` проверяет реальные prefix rights и отсутствие root credentials в API.
6. `make test-security-grade4` проверяет mTLS broker/Collector, включая чужой сертификат той же CA; `make test-acl-grade4` проверяет DB/Redis/Rabbit permissions.
7. `make rotate-leaf-grade4` удаляет старую LB URI из allowlist, проверяет old/expired deny и active leaf allow без rebuild.
8. `make test-telemetry-leak-grade4` сверяет Loki с credential probe и всеми локальными secret values, не печатая их.
## Bootstrap и эксплуатация
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
В Git находятся только генераторы, policy templates и public CA configuration. `secrets/`, `.operator/` и `volumes/` игнорируются. CA key, leaf keys, passwords, SecretID, root token и unseal share не входят в image layers и отчёт.
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 — хорошее расширение, но не обязательное название технологии.
Оператор выполняет `make up`. При первой инициализации OpenBao root/unseal JSON сохраняется отдельно от storage в `.operator` mode 0700/0600. App images не содержат постоянный bootstrap secret: service получает ограниченный по сроку SecretID через runtime mount, обменивает его на bounded token и читает один allowlisted KV path. После рестарта OpenBao sealed; `scripts/bootstrap-openbao.sh` читает operator file, выполняет unseal и обновляет policies/KV/SecretID, после чего app containers пересоздаются. Потеря operator file при initialized storage требует внешней резервной копии unseal material; приложение восстановить trust само не может.
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
`scripts/rotate-secret-grade4.sh` меняет worker RabbitMQ password в backend и scoped KV, пересоздаёт только worker с `--no-build` и доказывает old deny. `scripts/rotate-leaf-grade4.sh` выпускает новый LB client leaf, атомарно меняет cert/allowlist, пересоздаёт edge с `--no-build` и доказывает old/expired deny. Образа CA/root material не получают; фонового renewal agent нет, поэтому штатные 7 d SecretID и 365 d leaf обновляет оператор до expiry.
+101
View File
@@ -0,0 +1,101 @@
# Sanitized grade-3 evidence — 2026-11-18
No passwords, tokens, private keys, Authorization headers or user content are included.
## Toolchain
- Go 1.27.4 linux/amd64
- Docker Engine 29.7.2; Compose 5.5.0
- OpenSSL 3.5.5
- Intel Core i5-1135G7, 8 vCPU exposed to WSL, 3.7 GiB RAM
## Checks
```text
make check
PASS: offline skeleton structure, local refs and Python syntax
PYTHON=/tmp/lab7-venv/bin/python make validate
PASS: full OpenAPI 3.1 and JSON Schema validation
go test ./...
PASS
go vet ./...
PASS
make test
PASS: lab7 public API scenario
make test-security
PASS: trusted HTTPS works; untrusted CA rejected
make test-security-grade3
PASS: missing/foreign/wrong-identity LB certificates rejected
PASS: allowed LB identity accepted
PASS: API replicas have no published bypass port
PASS: telemetry missing/wrong identity rejected; Grafana identity accepted
make test-rate-limit-grade3
PASS: login limit is shared across replicas and returns 429 with Retry-After
make test-openbao-policy
PASS: own path allow; foreign path, policy admin and write deny
./tests/minio_policy.sh
PASS: staging write-only; attachments read-only; bucket create/anonymous GET deny
go run golang.org/x/vuln/cmd/govulncheck@latest ./...
No vulnerabilities found. (govulncheck v1.10.0)
```
## Argon2id benchmark
```text
BenchmarkHashPasswordGrade3-8 5 32716606 ns/op
```
Parameters: Argon2id `m=19456 KiB`, `t=2`, `p=1`; five fixed iterations. This is a local latency observation, not a universal target.
## Closed-loop synthetic load
```json
{
"workload": "closed-loop POST messages; no automatic retries",
"requested_duration_seconds": 30,
"elapsed_seconds": 30.094,
"concurrency": 4,
"successful_requests": 1959,
"failed_requests": 0,
"error_ratio": 0.0,
"successful_rps": 65.095,
"successful_latency_ms": {"p50": 87.901, "p95": 100.057, "p99": 106.397}
}
```
One `docker stats --no-stream` sample during the run:
| Container | CPU | Memory |
| --- | ---: | ---: |
| API-1 | 10.19% | 16.38 MiB / 256 MiB |
| API-2 | 11.07% | 21.20 MiB / 256 MiB |
| ingress | 25.09% | 23.41 MiB / 128 MiB |
| PostgreSQL | 13.89% | 68.33 MiB / 512 MiB |
Closed-loop percentiles cover successful requests only and include client overhead/coordinated omission.
## Failure hooks
```text
make test-persistence ACTION_SCRIPT=scripts/restart.sh
PASS: persistence preserved confirmed data and existing session
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
observed_instances_before=2
successful_writes=110
failed_attempts=8
first_recovery_seconds=4.932
PASS: confirmed data preserved; duplicate messages not observed
```
The persistence hook restarted PostgreSQL, Redis, MinIO, RabbitMQ, OpenBao and telemetry stores with volumes, performed operator unseal/bootstrap, then recreated the app processes. The failover hook stopped exactly the API instance named by its opaque `X-Instance-Id` and left the other replica serving.
+32
View File
@@ -0,0 +1,32 @@
# Санитизированное доказательство уровня 4
Дата воспроизведения: 2026-11-22. Стенд и ограничения нагрузки описаны в `REPORT.md`. Secret values, tokens, private keys и полные credential-bearing responses в этот файл не записывались.
## Identity, ACL и hardening
- `make test-security-grade4` — PASS. Broker отверг отсутствие client certificate, same-CA intruder и API identity без broker edge; принял отдельные worker/dispatcher identities. OTLP gateway отверг отсутствие cert и same-CA intruder; принял отдельные api/worker/dispatcher identities.
- Тот же сценарий подтвердил read-only rootfs, `no-new-privileges`, `cap_drop: ALL` у application containers и ограничения worker: 1 CPU, 512 MiB, `GOMEMLIMIT=448MiB`, concurrency 1, timeout 60 s.
- `tests/attachment_boundaries.py` — PASS. Ровно 10 MiB и 40 000 000 pixels обработаны; сразу после проверки worker использовал 426.3 MiB/512 MiB, `OOMKilled=false`.
- `make test-acl-grade4` — PASS. PostgreSQL использует `verify-full`; dispatcher имеет `SELECT,UPDATE` только для recovery attachment, не читает users и не удаляет attachments. Redis API user ограничен cache prefix и не управляет ACL; RabbitMQ producer/consumer permissions ограничены одной attachment queue. Реальный reaper восстановил найденную просроченную job после точечного grant.
- `make test-telemetry-leak-grade4` — PASS. Loki содержит structured application events, но не содержит уникальный wrong-password probe, Authorization/Basic/Bearer, request bodies и значения ignored secret files.
## Credential lifecycle
- `make rotate-secret-grade4` — PASS. RabbitMQ worker password заменён в backend и scoped OpenBao KV; старый credential отвергнут, новый принят; worker пересоздан с `--no-build`, image ID не изменился.
- `make rotate-leaf-grade4` — PASS. Выпущена новая уникальная LB URI identity; предыдущий и `days=0` leaf отвергнуты, новый принят; app/ingress image IDs не изменились.
- `make test-openbao-lifecycle-grade4` — PASS. One-use SecretID нельзя использовать повторно; renewable token работает после исходного TTL и прекращает работать на max TTL; при seal уже работающий API продолжает использовать загруженные credentials, новый API fail-closed; operator unseal восстанавливает запуск без rebuild.
## Password и login DoS
- `go test ./internal/security ./student_tests` — PASS. Legacy Argon2id PHC `m=8192,t=1` после успешной проверки заменяется текущим hash через compare-and-set; wrong password не запускает rehash.
- `make login-dos-benchmark` — `23485943 ns/op` (23.485943 ms/op на этом стенде). Общий PostgreSQL limiter выполняется до KDF и допускает 5 попыток за 60 s: измеренный верхний бюджет около 117 ms Argon2 CPU/min на один normalized identifier.
- `make test-rate-limit-grade3` — PASS: запросы распределились по обеим API replicas, первые пять дали 401, шестой — 429 с `Retry-After`.
- `make test-state-pruning-grade4` — PASS: bounded indexed cleanup удалил истёкшую limiter row, но сохранил активное окно с attempts=4. Session/idempotency и limiter batch ограничен 256 rows и запускается не чаще раза на 128 операций после первого запуска.
## Регрессия и сканирование
- `go test ./...`, `go vet ./...`, `make check`, полная `make validate`, `docker compose config --quiet` и `git diff --check` — PASS.
- `make test`, `make test-security-grade3`, `make test-openbao-policy`, `./tests/minio_policy.sh` — PASS; публичный контракт, предыдущий mTLS boundary и scoped policies не ослаблены.
- `make scan-grade4` — PASS по заявленной политике. `govulncheck v1.10.0`: no reachable vulnerabilities; strict Trivy 0.76.2: 0 HIGH/CRITICAL fixed для app и ingress. Обязательный informational scan архивированного upstream показал MinIO 40 HIGH/4 CRITICAL и `mc` 26 HIGH/1 CRITICAL; применимость, компенсирующие меры и production-блокер зафиксированы в `security/SCAN_TRIAGE.md`.
Все команды воспроизводимы из `REPORT.md`. Это локальная evidence summary, а не CI attestation или cryptographic provenance.
+61
View File
@@ -0,0 +1,61 @@
module mtusi2026lab7
go 1.27.1
require (
github.com/disintegration/imaging v1.6.2
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v5 v5.11.0
github.com/mayahiro/go-webp v0.4.0
github.com/minio/minio-go/v7 v7.4.1
github.com/rabbitmq/amqp091-go v1.14.0
github.com/redis/go-redis/v9 v9.23.0
go.opentelemetry.io/otel v1.46.0
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.22.0
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.46.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0
go.opentelemetry.io/otel/log v0.22.0
go.opentelemetry.io/otel/metric v1.46.0
go.opentelemetry.io/otel/sdk v1.46.0
go.opentelemetry.io/otel/sdk/log v0.22.0
go.opentelemetry.io/otel/sdk/metric v1.46.0
go.opentelemetry.io/otel/trace v1.46.0
golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2
golang.org/x/image v0.45.0
)
require (
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/klauspost/compress v1.20.2 // indirect
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
github.com/klauspost/crc32 v1.3.0 // indirect
github.com/minio/crc64nvme v1.1.1 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/rs/xid v1.6.0 // indirect
github.com/tinylib/msgp v1.6.4 // indirect
github.com/zeebo/xxh3 v1.1.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
go.uber.org/atomic v1.12.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/net v0.62.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.43.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 // indirect
google.golang.org/grpc v1.83.2 // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/ini.v1 v1.67.3 // indirect
)
+143
View File
@@ -0,0 +1,143 @@
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo=
github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
github.com/mayahiro/go-webp v0.4.0 h1:2uHEKvvSBREhAB7iDkYC/oZ4K9gbdigk63mLWPBugDQ=
github.com/mayahiro/go-webp v0.4.0/go.mod h1:Z1wt6V5/6f7pUwPsfhA6EbHb7ZhIcoQ7k7/tY9JNG4c=
github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI=
github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
github.com/minio/minio-go/v7 v7.4.1 h1:PtU/zIOfQRWZ+QydXAZysc+xZYHdG+BBR4Z6TUvy73w=
github.com/minio/minio-go/v7 v7.4.1/go.mod h1:nQnQi7zTfXR4lREtYXZQWqo5aw0Rqv+ZqCGrTORygRk=
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek=
github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ=
github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.22.0 h1:lYk7RmxdLK865qLwibroNGldHa1U7SWKYYvNjlK7PIo=
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.22.0/go.mod h1:6GvlND0H0xdUJanOtIAn0xfwLkauh1tmsYEEVSMDdqY=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.46.0 h1:AP23h/mFgb/lc7tdck1Kfn9qxsM8TAeNPCU5C3pzaps=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.46.0/go.mod h1:K4EqCe1b4kGk5WR690ntg9LaBfsPoV32FwthbyoptuA=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 h1:KrC1YrQeSt46ITMWAbgQx1M1eV1/1TKzttrBzymPmss=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0/go.mod h1:zDSEzoEqsOrgBeGvH66KRgxh90VonFyJqBHA0Pk3+rM=
go.opentelemetry.io/otel/log v0.22.0 h1:5DBNnfvaJ6CVdkJ+Jle8Tzs50aSSv49TXGj9XRsEYw0=
go.opentelemetry.io/otel/log v0.22.0/go.mod h1:gzOt/R67vF2GniAqWu8Qv0SXy89f71muHcrkz76PCdc=
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
go.opentelemetry.io/otel/metric/x v0.68.0 h1:TA/cBT23D3MnxYPwHL7YFOdYGdx0A0v+s7Mzotpd1dU=
go.opentelemetry.io/otel/metric/x v0.68.0/go.mod h1:agudOmvWhwUTjgibWDzxD2PoWYnpw5Ht5jISYOD2Hd4=
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=
go.opentelemetry.io/otel/sdk/log v0.22.0 h1:PRL+s6P63XT4E/bheEflopPUpVxuvANqZwtt89yhoGk=
go.opentelemetry.io/otel/sdk/log v0.22.0/go.mod h1:JNp0sBELrjCTcu5W3GzABVypeU6vDJjBS+X0JISuz+g=
go.opentelemetry.io/otel/sdk/log/logtest v0.22.0 h1:infPnfNrhCNgOUZRs3gWUg8vhoBUHihq02gwK05gzlg=
go.opentelemetry.io/otel/sdk/log/logtest v0.22.0/go.mod h1:gkQZA3z15Bv3KU9vigBTi8dFechSozRP7v94X4VZv+s=
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2 h1:zGDaB+/Mus2mScKvZ23k+W9NAUbP56sNM9SptgvWI5A=
golang.org/x/crypto v0.58.1-0.20261009181718-2f1f834330b2/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
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-20260819154853-08b0e4226688 h1:ax2KzoSRIZU/M0cIxri3pKxy99vniH1PVxWC6si/eZI=
google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688/go.mod h1:1RJ9BQGyNdZwkGc1eTqkErfRZ6RJyYPHZo73BZ1vQqI=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 h1:cYNAzI2sUwhmCcoj9TxvihSrqsxt6uIkj3rDRhSDmW4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw=
gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+28 -4
View File
@@ -1,7 +1,31 @@
# Инфраструктура студента
# Инфраструктура lab7
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
Основная запускаемая топология находится в `compose.yaml`; `compose.example.yaml` остаётся worksheet задания и не используется. Версии, healthchecks, volumes, internal networks и CPU/RAM limits зафиксированы в Compose.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
| Роль | Service | Storage | Доступ |
| --- | --- | --- | --- |
| TLS ingress/LB | `ingress` / HAProxy 3.2 | stateless | `127.0.0.1:8443`; mTLS к API |
| API | `api` ×2 / локальный Go image | PostgreSQL/S3 | internal 8444 only |
| Source of truth | `postgres` 16.15 | `postgres_data` | native TLS, internal only |
| Cache | `redis` 8.10.2 | ephemeral | TLS gateway + ACL |
| Objects | `minio` pinned last release | `minio_data` | TLS gateway, scoped API/worker users; archived upstream risk в `security/SCAN_TRIAGE.md` |
| Jobs | `broker` RabbitMQ 4.1.4 | `broker_data` | TLS gateway, producer/consumer ACL |
| Secrets | `openbao` 2.4.4 | `volumes/openbao` | TLS, AppRole; operator port 18200 |
| Telemetry | Collector 0.165, Prometheus 3.16, Loki 3.7.9, Tempo 2.10.5, Grafana 13.3 | named volumes | TLS/mTLS gateway; admin ports loopback |
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
`scripts/bootstrap-dependencies.sh` выполняет migrations, создаёт DB roles/GRANT, private bucket/MinIO policies и RabbitMQ identities/ACL. `scripts/bootstrap-openbao.sh` выполняет operator init/unseal и AppRole/policy/KV bootstrap. Оба сценария повторяемы и не печатают secret values.
Worker намеренно ограничен одной тяжёлой image job одновременно: 1 CPU, 512 MiB, `GOMEMLIMIT=448MiB`, timeout 60 s. Истёкшие auth/idempotency rows удаляются небольшими индексированными batch, а dispatcher получает `UPDATE` attachments только для lease recovery.
```sh
make up
docker compose ps
make test
make test-security-grade4
make test-acl-grade4
make test-state-pruning-grade4
make test-telemetry-leak-grade4
make scan-grade4
```
`scripts/restart.sh` перезапускает реальные stores с сохранением volumes и требует operator unseal. `scripts/stop-one.sh` останавливает ровно одну API-реплику по opaque instance id. `scripts/rotate-secret-grade4.sh` и `scripts/rotate-leaf-grade4.sh` доказывают rotation/revocation без пересборки image. `make cleanup-lab` сохраняет named volumes, ignored operator material и pulled third-party images.
+66 -4
View File
@@ -1,7 +1,69 @@
# OpenBao — реализовать конфигурацию и политики
# OpenBao в lab7
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
Рабочие файлы находятся в `infrastructure/openbao`; эта папка описывает operator procedure. Используется OpenBao 2.4.4 не в dev-mode: file storage `volumes/openbao`, TLS 1.3 listener 8200 и отключённый UI. Host публикует TLS endpoint только на `127.0.0.1:18200`.
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
## Первый запуск
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
```sh
./scripts/init-secrets.sh
docker compose up -d openbao
./scripts/bootstrap-openbao.sh
```
Bootstrap идемпотентно:
1. выполняет `operator init` только для нового storage;
2. сохраняет root token и unseal share в ignored `.operator/openbao-init.json` (directory 0700, file 0600);
3. выполняет unseal по явному запуску оператором;
4. включает KV v2 `secret/` и AppRole;
5. записывает policies и локально подготовленные `secret/{api,worker,dispatcher}`;
6. выдаёт отдельные role ID/SecretID в ignored `secrets/openbao` mode 0600.
Скрипт не печатает root token, share, service tokens или secret values. `.operator` не монтируется в app/worker/dispatcher и не находится в OpenBao storage. Для реального использования operator file нужно хранить в отдельном защищённом backup; threshold 1/1 — явное упрощение однооператорного учебного стенда.
## Политики и lifecycle
- `api-policy.hcl`: `read` только `secret/data/api`.
- `worker-policy.hcl`: `read` только `secret/data/worker`.
- `dispatcher-policy.hcl`: `read` только `secret/data/dispatcher`.
- App token TTL 15 минут, max TTL 30 минут.
- SecretID TTL 168 часов. Приложение получает token через AppRole, читает allowlisted keys один раз при старте и не хранит token как постоянный `BAO_TOKEN`.
`internal/secrets/openbao.go` требует HTTPS, local CA, TLS 1.3, запрещает redirects и переносит в environment только имена из `BAO_ENV_KEYS`. Неизвестный/отсутствующий ключ завершает startup ошибкой.
Проверка реальных allow/deny:
```sh
make test-openbao-policy
```
Ожидается: API own path allow; worker path, policy administration и KV write deny.
Проверка lifecycle использует отдельную временную AppRole с one-use SecretID и token TTL 10 s/max 24 s, не изменяя штатные роли:
```sh
make test-openbao-lifecycle-grade4
```
Сценарий доказывает запрет повторного SecretID, renewal после исходного TTL, окончательный expiry на max TTL, сохранение уже загруженных credentials у работающего API при seal, fail-closed нового API и восстановление после operator unseal без rebuild.
## Restart и восстановление
OpenBao после restart sealed. Работающие процессы продолжают использовать уже прочитанные downstream credentials, но новый процесс fail-closed не запустится. Оператор выполняет:
```sh
./scripts/bootstrap-openbao.sh
docker compose up -d --force-recreate api worker dispatcher
```
Полный проверенный сценарий с рестартом stores, unseal и сохранением данных:
```sh
make test-persistence ACTION_SCRIPT=scripts/restart.sh
```
Если persistent storage initialized, а `.operator/openbao-init.json` потерян, скрипт останавливается и требует от оператора восстановить unseal material из защищённой копии. Он не переинициализирует storage и не создаёт новый root trust автоматически.
## Компрометация
Для скомпрометированного service operator отзывает его SecretID/token, создаёт новый SecretID и пересоздаёт только этот контейнер. Статические downstream credentials меняются в соответствующем backend и KV, затем service пересоздаётся. `make rotate-secret-grade4` проверяет этот процесс для рабочего RabbitMQ password: старое значение отозвано, новое принято, image ID не меняется. `make rotate-leaf-grade4` аналогично заменяет LB leaf и runtime URI allowlist, после чего старый и просроченный leaf отвергаются. Фоновый agent автоматической ротации, CA rollover и CRL/OCSP не реализованы.
+18 -4
View File
@@ -1,7 +1,21 @@
# Конфигурация наблюдаемости — реализовать
# Наблюдаемость lab7
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Реальные конфиги находятся в `infrastructure/telemetry`. API/worker/dispatcher экспортируют OTLP/HTTP через TLS gateway 4318 в Collector. Collector применяет memory limiter 192 MiB и batch, затем:
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
- metrics предоставляет Prometheus exporter 8889;
- traces отправляет по mTLS в Tempo через gateway 4319;
- logs отправляет по mTLS в Loki через gateway 3100.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Prometheus scrape 8888/8889 и Grafana data sources также используют отдельные mTLS client identities. Backend plaintext listeners присутствуют только на отдельных `internal: true` local networks с TLS gateway; host ports loopback. Grafana anonymous access отключён, admin password поступает через file secret.
Collector не получает HTTP Authorization/session headers и message body из instrumentation. Queue/retry ограничены: два consumers, queue 256, max elapsed retry 30 s; переполнение не превращается в неограниченный рост RAM.
```sh
docker compose logs otel-collector
docker compose ps telemetry-gateway prometheus loki tempo grafana
make test-security-grade3
make test-security-grade4
make test-telemetry-leak-grade4
```
Ожидаемые признаки: Collector `Everything is ready`, gateway backends UP; Prometheus identity проходит scrape, а missing/LB identity к data-source port отклоняется. OTLP gateway требует разные exact-CN identities `api`, `worker`, `dispatcher`: отсутствие сертификата и same-CA intruder отклоняются. Leak-тест отправляет уникальный credential probe, затем подтверждает наличие structured events и отсутствие probe, Authorization/Basic/Bearer, request body и всех локальных secret values в Loki. Alert/incident набор lab6 сохранён.
+33
View File
@@ -0,0 +1,33 @@
global
log stdout format raw local0
maxconn 1024
defaults
log global
mode tcp
timeout connect 3s
timeout client 60s
timeout server 60s
frontend s3_tls
bind :9000 ssl crt /run/secrets/dependency_pem ssl-min-ver TLSv1.3
mode http
default_backend s3_plain
backend s3_plain
mode http
server minio minio:9000 check
frontend broker_tls
bind :5671 ssl crt /run/secrets/dependency_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3
acl worker_identity ssl_c_s_dn(cn) -m str worker
acl dispatcher_identity ssl_c_s_dn(cn) -m str dispatcher
tcp-request content reject unless worker_identity or dispatcher_identity
default_backend broker_plain
backend broker_plain
server broker broker:5672 check
frontend redis_tls
bind :6380 ssl crt /run/secrets/dependency_pem ssl-min-ver TLSv1.3
default_backend redis_plain
backend redis_plain
server redis redis:6379 check
+75
View File
@@ -0,0 +1,75 @@
global
log stdout format raw local0
maxconn 2048
defaults
log global
mode http
timeout connect 3s
timeout client 60s
timeout server 60s
frontend otlp_tls
bind :4318 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required alpn h2,http/1.1 ssl-min-ver TLSv1.3
acl api_identity ssl_c_s_dn(cn) -m str api
acl worker_identity ssl_c_s_dn(cn) -m str worker
acl dispatcher_identity ssl_c_s_dn(cn) -m str dispatcher
http-request deny deny_status 403 unless api_identity or worker_identity or dispatcher_identity
default_backend collector_otlp
backend collector_otlp
server collector otel-collector:4318 check
frontend collector_metrics_tls
bind :8889 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3
acl prometheus_identity ssl_c_s_dn(cn) -m str prometheus
http-request deny deny_status 403 unless prometheus_identity
default_backend collector_metrics
backend collector_metrics
server collector otel-collector:8889 check
frontend collector_internal_tls
bind :8888 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3
acl prometheus_identity ssl_c_s_dn(cn) -m str prometheus
http-request deny deny_status 403 unless prometheus_identity
default_backend collector_internal
backend collector_internal
server collector otel-collector:8888 check
frontend loki_tls
bind :3100 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3
acl collector_identity ssl_c_s_dn(cn) -m str otel-collector
acl grafana_identity ssl_c_s_dn(cn) -m str grafana
http-request deny deny_status 403 unless collector_identity or grafana_identity
default_backend loki_plain
backend loki_plain
server loki loki:3100 check
frontend tempo_query_tls
bind :3200 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3
acl grafana_identity ssl_c_s_dn(cn) -m str grafana
http-request deny deny_status 403 unless grafana_identity
default_backend tempo_query
backend tempo_query
server tempo tempo:3200 check
frontend tempo_otlp_tls
bind :4319 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3
acl collector_identity ssl_c_s_dn(cn) -m str otel-collector
http-request deny deny_status 403 unless collector_identity
default_backend tempo_otlp
backend tempo_otlp
server tempo tempo:4318 check
frontend prometheus_tls
bind :9090 ssl crt /run/secrets/telemetry_pem ca-file /run/secrets/tls_ca verify required ssl-min-ver TLSv1.3
acl grafana_identity ssl_c_s_dn(cn) -m str grafana
http-request deny deny_status 403 unless grafana_identity
default_backend prometheus_plain
backend prometheus_plain
server prometheus prometheus:9090 check
frontend grafana_tls
bind :3000 ssl crt /run/secrets/telemetry_pem alpn h2,http/1.1 ssl-min-ver TLSv1.3
default_backend grafana_plain
backend grafana_plain
server grafana grafana:3000 check
+8
View File
@@ -0,0 +1,8 @@
FROM haproxy:3.2-alpine@sha256:dfba86f031bd4c9039f10f8cc5de75991d1b6766d5460f0335b980408503baad
COPY infrastructure/haproxy/haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg
USER 1000:1000
EXPOSE 8443
+31
View File
@@ -0,0 +1,31 @@
global
log stdout format raw local0
maxconn 2048
defaults
log global
mode http
option httplog
timeout connect 3s
timeout client 30s
timeout server 30s
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
frontend public_https
bind :8443 ssl crt /run/secrets/ingress_pem alpn h2,http/1.1 ssl-min-ver TLSv1.3
http-request set-header X-Forwarded-Proto https
default_backend api_mtls
backend api_mtls
balance leastconn
option httpchk
http-check send meth GET uri /health/lb ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server check inter 2s fall 2 rise 2 resolvers docker init-addr libc,none ssl ssl-min-ver TLSv1.3 verify required verifyhost api ca-file /run/secrets/tls_ca crt /run/secrets/lb_client_pem
server-template api 8 api:8444
+43
View File
@@ -0,0 +1,43 @@
FROM golang:1.27.3-alpine@sha256:fa3d596898d9f126af7c01d14ee7597bab3f39cccf392ef36b69fe77cd681f18 AS minio-builder
ARG MINIO_VERSION=RELEASE.2025-10-15T17-29-55Z
RUN CGO_ENABLED=0 GOBIN=/out go install github.com/minio/minio@${MINIO_VERSION}
FROM golang:1.27.3-alpine@sha256:fa3d596898d9f126af7c01d14ee7597bab3f39cccf392ef36b69fe77cd681f18 AS mc-builder
ARG MC_VERSION=RELEASE.2025-08-13T08-35-41Z
RUN CGO_ENABLED=0 GOBIN=/out go install github.com/minio/mc@${MC_VERSION}
FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf AS server
RUN apk upgrade --no-cache && \
apk add --no-cache ca-certificates wget && \
addgroup -g 1000 minio && \
adduser -u 1000 -G minio -s /sbin/nologin -D minio && \
mkdir -p /data && \
chown minio:minio /data
COPY --from=minio-builder /out/minio /usr/local/bin/minio
USER minio:minio
VOLUME ["/data"]
EXPOSE 9000
HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=20 \
CMD wget -qO- http://127.0.0.1:9000/minio/health/live >/dev/null || exit 1
ENTRYPOINT ["/usr/local/bin/minio"]
CMD ["server", "/data", "--address", ":9000"]
FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf AS client
RUN apk upgrade --no-cache && \
apk add --no-cache ca-certificates && \
addgroup -g 1000 minio && \
adduser -u 1000 -G minio -s /sbin/nologin -D minio
COPY --from=mc-builder /out/mc /usr/local/bin/mc
USER minio:minio
ENTRYPOINT ["/usr/local/bin/mc"]
@@ -0,0 +1,20 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
"Resource": ["arn:aws:s3:::__BUCKET__"]
},
{
"Effect": "Allow",
"Action": ["s3:PutObject"],
"Resource": ["arn:aws:s3:::__BUCKET__/staging/*"]
},
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::__BUCKET__/attachments/*"]
}
]
}
@@ -0,0 +1,20 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
"Resource": ["arn:aws:s3:::__BUCKET__"]
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::__BUCKET__/staging/*"]
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::__BUCKET__/attachments/*"]
}
]
}
+16
View File
@@ -0,0 +1,16 @@
FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f AS frontend-build
WORKDIR /frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
RUN npm test && npm run build
FROM nginx:1.30.6-alpine@sha256:970364228b1e4f932abc22d321932816782cca8a20b85a77552a7cfe9acfb3b5
COPY infrastructure/nginx/nginx.conf /etc/nginx/nginx.conf
COPY --from=frontend-build /frontend/dist /usr/share/nginx/html
EXPOSE 8080
+33
View File
@@ -0,0 +1,33 @@
worker_processes auto;
events {
worker_connections 512;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
server {
listen 8080;
server_name _;
root /usr/share/nginx/html;
index index.html;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer" always;
add_header X-Frame-Options "DENY" always;
add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
location /assets/ {
try_files $uri =404;
expires 1y;
add_header Cache-Control "public, immutable";
}
location / {
try_files $uri $uri/ /index.html;
}
}
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/data/api" {
capabilities = ["read"]
}
+15
View File
@@ -0,0 +1,15 @@
ui = false
disable_mlock = true
storage "file" {
path = "/openbao/data"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/run/secrets/openbao_cert"
tls_key_file = "/run/secrets/openbao_key"
tls_min_version = "tls13"
}
api_addr = "https://openbao:8200"
@@ -0,0 +1,3 @@
path "secret/data/dispatcher" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/data/worker" {
capabilities = ["read"]
}
@@ -0,0 +1,81 @@
{
"annotations": {"list": []},
"editable": false,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"id": null,
"links": [],
"liveNow": false,
"panels": [
{
"datasource": {"type": "prometheus", "uid": "prometheus"},
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 0},
"id": 1,
"options": {"legend": {"displayMode": "table", "placement": "bottom"}},
"targets": [{"expr": "sum(rate(messenger_http_server_requests_total[1m]))", "legendFormat": "all requests", "refId": "A"}],
"title": "API request rate",
"type": "timeseries"
},
{
"datasource": {"type": "prometheus", "uid": "prometheus"},
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 0},
"id": 2,
"options": {"legend": {"displayMode": "table", "placement": "bottom"}},
"targets": [{"expr": "sum by (status_class) (rate(messenger_http_server_requests_total[1m]))", "legendFormat": "{{status_class}}", "refId": "A"}],
"title": "API responses by status class",
"type": "timeseries"
},
{
"datasource": {"type": "prometheus", "uid": "prometheus"},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 0},
"id": 3,
"options": {"legend": {"displayMode": "table", "placement": "bottom"}},
"targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "A"}],
"title": "API duration",
"type": "timeseries"
},
{
"datasource": {"type": "prometheus", "uid": "prometheus"},
"fieldConfig": {"defaults": {"unit": "jobs"}, "overrides": []},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 8},
"id": 4,
"options": {"legend": {"displayMode": "table", "placement": "bottom"}},
"targets": [{"expr": "sum by (outcome) (increase(messenger_worker_jobs_total[5m]))", "legendFormat": "{{outcome}}", "refId": "A"}],
"title": "Worker jobs by outcome",
"type": "timeseries"
},
{
"datasource": {"type": "prometheus", "uid": "prometheus"},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 8},
"id": 5,
"options": {"legend": {"displayMode": "table", "placement": "bottom"}},
"targets": [{"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_worker_job_duration_seconds_bucket[5m])))", "legendFormat": "p95 {{outcome}}", "refId": "A"}],
"title": "Worker processing duration",
"type": "timeseries"
},
{
"datasource": {"type": "loki", "uid": "loki"},
"gridPos": {"h": 10, "w": 24, "x": 0, "y": 16},
"id": 6,
"options": {"dedupStrategy": "none", "enableLogDetails": true, "showCommonLabels": false, "showLabels": false, "showTime": true, "sortOrder": "Descending", "wrapLogMessage": true},
"targets": [{"expr": "{service_name=~\"messenger-(api|worker)\"}", "queryType": "range", "refId": "A"}],
"title": "Correlated structured logs",
"type": "logs"
}
],
"refresh": "5s",
"schemaVersion": 41,
"tags": ["mtusi", "lab6", "grade3"],
"templating": {"list": []},
"time": {"from": "now-15m", "to": "now"},
"timepicker": {},
"timezone": "browser",
"title": "MTUSI Lab 6 — Grade 3",
"uid": "mtusi-lab7-grade3",
"version": 1
}
@@ -0,0 +1,544 @@
{
"annotations": {
"list": []
},
"editable": false,
"graphTooltip": 1,
"id": null,
"links": [],
"panels": [
{
"id": 1,
"title": "API RPS",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 6,
"x": 0,
"y": 0
},
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_server_requests_total[1m]))",
"legendFormat": "requests/s"
}
]
},
{
"id": 2,
"title": "API 5xx ratio",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 6,
"x": 6,
"y": 0
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_server_requests_total{status_class=\"5xx\"}[1m])) / clamp_min(sum(rate(messenger_http_server_requests_total[1m])), 0.000001)",
"legendFormat": "5xx / all"
}
]
},
{
"id": 3,
"title": "API latency p50/p95/p99",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 0
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_server_duration_seconds_bucket[5m])))",
"legendFormat": "p99"
}
]
},
{
"id": 4,
"title": "Queue depth / oldest age seconds",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 7
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_queue_depth)",
"legendFormat": "depth"
},
{
"refId": "B",
"expr": "max(messenger_queue_oldest_job_age_seconds)",
"legendFormat": "oldest age s"
}
]
},
{
"id": 5,
"title": "Worker saturation",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 8,
"y": 7
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_worker_busy) / clamp_min(max(messenger_worker_capacity), 1)",
"legendFormat": "busy / capacity"
}
]
},
{
"id": 6,
"title": "Time to ready p50/p95/p99",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 16,
"y": 7
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[5m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[5m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[5m])))",
"legendFormat": "p99"
}
]
},
{
"id": 7,
"title": "PostgreSQL pool used/idle/capacity",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 14
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name, state) (messenger_db_pool_connections)",
"legendFormat": "{{service_name}} {{state}}"
}
]
},
{
"id": 8,
"title": "PostgreSQL pool waits",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 8,
"y": 14
},
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name) (rate(messenger_db_pool_waits_total[5m]))",
"legendFormat": "{{service_name}} waits/s"
}
]
},
{
"id": 9,
"title": "Process CPU",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 16,
"y": 14
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name) (rate(messenger_process_cpu_time_seconds_total[5m]))",
"legendFormat": "{{service_name}}"
}
]
},
{
"id": 10,
"title": "Process RSS",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 21
},
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "max by (service_name) (messenger_process_memory_bytes)",
"legendFormat": "{{service_name}}"
}
]
},
{
"id": 11,
"title": "Worker jobs and p95 duration",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 8,
"y": 21
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(messenger_worker_jobs_total[5m]))",
"legendFormat": "jobs/s {{outcome}}"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_worker_job_duration_seconds_bucket[5m])))",
"legendFormat": "p95 s {{outcome}}"
}
]
},
{
"id": 12,
"title": "Collector bounded queues / drops",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 16,
"y": 21
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "otelcol_exporter_queue_size",
"legendFormat": "queue {{exporter}}"
},
{
"refId": "B",
"expr": "otelcol_exporter_queue_capacity",
"legendFormat": "capacity {{exporter}}"
},
{
"refId": "C",
"expr": "(sum(rate(otelcol_exporter_send_failed_log_records[5m])) or vector(0)) + (sum(rate(otelcol_exporter_send_failed_spans[5m])) or vector(0))",
"legendFormat": "drops/s"
}
]
},
{
"id": 13,
"title": "Alert state",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"h": 7,
"w": 8,
"x": 0,
"y": 28
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "table",
"placement": "bottom"
}
},
"targets": [
{
"refId": "A",
"expr": "ALERTS{alertname=~\"Messenger(APIHighErrorRate|QueueLagGrowing)\"}",
"legendFormat": "{{alertname}} {{alertstate}}"
}
]
},
{
"id": 14,
"title": "Correlated logs",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"h": 10,
"w": 16,
"x": 8,
"y": 28
},
"targets": [
{
"refId": "A",
"expr": "{service_name=~\"messenger-(api|worker|dispatcher)\"}",
"queryType": "range"
}
],
"options": {
"dedupStrategy": "none",
"enableLogDetails": true,
"showCommonLabels": false,
"showLabels": false,
"showTime": true,
"sortOrder": "Descending",
"wrapLogMessage": true
}
}
],
"refresh": "5s",
"schemaVersion": 41,
"tags": [
"mtusi",
"lab6",
"grade4"
],
"templating": {
"list": []
},
"time": {
"from": "now-30m",
"to": "now"
},
"timepicker": {},
"timezone": "browser",
"title": "MTUSI Lab 6 - Grade 4",
"uid": "mtusi-lab7-grade4",
"version": 1
}
@@ -0,0 +1,70 @@
{
"annotations": {"list": []},
"editable": false,
"graphTooltip": 1,
"id": null,
"panels": [
{
"id": 1,
"title": "API error ratio by burn window",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 9, "w": 12, "x": 0, "y": 0},
"fieldConfig": {"defaults": {"unit": "percentunit"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "messenger:sli_api_error_ratio_30s", "legendFormat": "30s"},
{"refId": "B", "expr": "messenger:sli_api_error_ratio_1m", "legendFormat": "1m"},
{"refId": "C", "expr": "messenger:sli_api_error_ratio_2m", "legendFormat": "2m"},
{"refId": "D", "expr": "messenger:sli_api_error_ratio_5m", "legendFormat": "5m"}
]
},
{
"id": 2,
"title": "Attachment >10s ratio by burn window",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 9, "w": 12, "x": 12, "y": 0},
"fieldConfig": {"defaults": {"unit": "percentunit"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "messenger:sli_attachment_slow_ratio_30s", "legendFormat": "30s"},
{"refId": "B", "expr": "messenger:sli_attachment_slow_ratio_1m", "legendFormat": "1m"},
{"refId": "C", "expr": "messenger:sli_attachment_slow_ratio_2m", "legendFormat": "2m"},
{"refId": "D", "expr": "messenger:sli_attachment_slow_ratio_5m", "legendFormat": "5m"}
]
},
{
"id": 3,
"title": "SLO compliance (7d policy window)",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 9},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"targets": [
{"refId": "A", "expr": "messenger:slo_api_success_ratio_7d", "legendFormat": "API success"},
{"refId": "B", "expr": "messenger:slo_attachment_ready_ratio_7d", "legendFormat": "ready <=10s"},
{"refId": "C", "expr": "vector(0.99)", "legendFormat": "99% objective"}
]
},
{
"id": 4,
"title": "Burn-rate alert states",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 9},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "ALERTS{alertname=~\"Messenger(API|AttachmentReady)BurnRate(Fast|Slow)\"}", "legendFormat": "{{alertname}} {{alertstate}}"}
]
}
],
"refresh": "5s",
"schemaVersion": 42,
"tags": ["mtusi", "lab6", "grade5", "slo", "burn-rate"],
"templating": {"list": []},
"time": {"from": "now-30m", "to": "now"},
"timezone": "browser",
"title": "MTUSI Lab 6 - Grade 5 SLO",
"uid": "mtusi-lab7-grade5",
"version": 1
}
@@ -0,0 +1,13 @@
apiVersion: 1
providers:
- name: MTUSI Lab 6
orgId: 1
folder: Lab 6
type: file
disableDeletion: true
editable: false
updateIntervalSeconds: 10
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,45 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://telemetry-gateway:9090
isDefault: true
editable: false
- name: Loki
uid: loki
type: loki
access: proxy
url: https://telemetry-gateway:3100
editable: false
jsonData:
derivedFields:
- name: TraceID
matcherRegex: '([0-9a-f]{32})'
datasourceUid: tempo
url: '$${__value.raw}'
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://telemetry-gateway:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: -1m
spanEndTimeShift: 1m
tags:
- key: service.name
value: service_name
filterByTraceID: true
filterBySpanID: true
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
+35
View File
@@ -0,0 +1,35 @@
auth_enabled: false
server:
http_listen_port: 3100
common:
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: 168h
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
@@ -0,0 +1,81 @@
extensions:
health_check:
endpoint: 0.0.0.0:13133
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 48
batch:
timeout: 1s
send_batch_size: 256
send_batch_max_size: 512
exporters:
prometheus:
endpoint: 0.0.0.0:8889
resource_constant_labels:
included: [service.name, service.version, service.instance.id, deployment.environment.name]
otlp_http/tempo:
endpoint: https://telemetry-gateway:4319
tls:
ca_file: /run/secrets/tls_ca
cert_file: /run/secrets/collector_client_cert
key_file: /run/secrets/collector_client_key
timeout: 3s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 256
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 5s
max_elapsed_time: 30s
otlp_http/loki:
endpoint: https://telemetry-gateway:3100/otlp
tls:
ca_file: /run/secrets/tls_ca
cert_file: /run/secrets/collector_client_cert
key_file: /run/secrets/collector_client_key
timeout: 3s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 256
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 5s
max_elapsed_time: 30s
service:
extensions: [health_check]
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/tempo]
telemetry:
logs:
level: info
metrics:
level: detailed
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
@@ -0,0 +1,24 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files:
- /etc/prometheus/rules/*.yaml
scrape_configs:
- job_name: application-telemetry
scheme: https
tls_config:
ca_file: /run/secrets/tls_ca
server_name: telemetry-gateway
cert_file: /run/secrets/prometheus_client_cert
key_file: /run/secrets/prometheus_client_key
static_configs:
- targets: [telemetry-gateway:8889]
- job_name: collector-internal
scheme: https
tls_config:
ca_file: /run/secrets/tls_ca
server_name: telemetry-gateway
cert_file: /run/secrets/prometheus_client_cert
key_file: /run/secrets/prometheus_client_key
static_configs:
- targets: [telemetry-gateway:8888]
@@ -0,0 +1,98 @@
groups:
- name: messenger-level4
interval: 5s
rules:
- record: messenger:sli_api_success_ratio_5m
expr: 1 - (sum(rate(messenger_http_server_requests_total{status_class="5xx"}[5m])) / clamp_min(sum(rate(messenger_http_server_requests_total[5m])), 0.000001))
- alert: MessengerAPIHighErrorRate
expr: (sum(rate(messenger_http_server_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_server_requests_total[1m])), 0.000001)) > 0.01 and sum(rate(messenger_http_server_requests_total[1m])) > 0.05
for: 10s
labels:
severity: warning
slo: api-availability
annotations:
summary: API 5xx ratio exceeds the 99% availability SLO
description: More than 1% of business HTTP requests were 5xx during the last minute.
runbook: infrastructure/telemetry/runbooks/level4.md#api-high-error-rate
- alert: MessengerQueueLagGrowing
expr: max(messenger_queue_depth) > 0 and max(messenger_queue_oldest_job_age_seconds) > 10
for: 10s
labels:
severity: warning
slo: attachment-ready
annotations:
summary: Attachment queue lag is growing
description: At least one job has remained queued for more than 10 seconds.
runbook: infrastructure/telemetry/runbooks/level4.md#queue-lag-growing
- name: messenger-level5-burn-rate
interval: 5s
rules:
- record: messenger:slo_api_success_ratio_7d
expr: (1 - (sum(increase(messenger_http_server_requests_total{status_class="5xx"}[7d])) / clamp_min(sum(increase(messenger_http_server_requests_total[7d])), 1))) and sum(increase(messenger_http_server_requests_total[7d])) > 0
- record: messenger:slo_attachment_ready_ratio_7d
expr: (sum(increase(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[7d])) / clamp_min(sum(increase(messenger_attachment_ready_duration_seconds_count[7d])), 1)) and sum(increase(messenger_attachment_ready_duration_seconds_count[7d])) > 0
- record: messenger:sli_api_error_ratio_30s
expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[30s])) / clamp_min(sum(rate(messenger_http_server_requests_total[30s])), 0.000001)
- record: messenger:sli_api_error_ratio_1m
expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_server_requests_total[1m])), 0.000001)
- record: messenger:sli_api_error_ratio_2m
expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[2m])) / clamp_min(sum(rate(messenger_http_server_requests_total[2m])), 0.000001)
- record: messenger:sli_api_error_ratio_5m
expr: sum(rate(messenger_http_server_requests_total{status_class="5xx"}[5m])) / clamp_min(sum(rate(messenger_http_server_requests_total[5m])), 0.000001)
- record: messenger:sli_attachment_slow_ratio_30s
expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[30s])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[30s]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[30s])), 0.000001)
- record: messenger:sli_attachment_slow_ratio_1m
expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[1m])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[1m]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[1m])), 0.000001)
- record: messenger:sli_attachment_slow_ratio_2m
expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[2m])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[2m]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[2m])), 0.000001)
- record: messenger:sli_attachment_slow_ratio_5m
expr: (sum(rate(messenger_attachment_ready_duration_seconds_count[5m])) - sum(rate(messenger_attachment_ready_duration_seconds_bucket{le="10.0"}[5m]))) / clamp_min(sum(rate(messenger_attachment_ready_duration_seconds_count[5m])), 0.000001)
- alert: MessengerAPIBurnRateFast
expr: messenger:sli_api_error_ratio_30s > (14.4 * 0.01) and messenger:sli_api_error_ratio_2m > (14.4 * 0.01) and sum(rate(messenger_http_server_requests_total[30s])) > 0.1
for: 10s
labels:
severity: page
slo: api-availability
burn_rate: fast
annotations:
summary: API consumes the 1% error budget at fast burn rate
description: Both 30s and 2m windows exceed 14.4x burn rate.
runbook: infrastructure/telemetry/runbooks/level5.md#api-burn-rate
- alert: MessengerAPIBurnRateSlow
expr: messenger:sli_api_error_ratio_1m > (6 * 0.01) and messenger:sli_api_error_ratio_5m > (6 * 0.01) and sum(rate(messenger_http_server_requests_total[1m])) > 0.05
for: 20s
labels:
severity: ticket
slo: api-availability
burn_rate: slow
annotations:
summary: API consumes the 1% error budget at sustained burn rate
description: Both 1m and 5m windows exceed 6x burn rate.
runbook: infrastructure/telemetry/runbooks/level5.md#api-burn-rate
- alert: MessengerAttachmentReadyBurnRateFast
expr: messenger:sli_attachment_slow_ratio_30s > (14.4 * 0.01) and messenger:sli_attachment_slow_ratio_2m > (14.4 * 0.01) and sum(rate(messenger_attachment_ready_duration_seconds_count[30s])) > 0
for: 10s
labels:
severity: page
slo: attachment-ready
burn_rate: fast
annotations:
summary: Attachment ready latency consumes its error budget quickly
description: More than 14.4% of completed attachments exceed 10s in both windows.
runbook: infrastructure/telemetry/runbooks/level5.md#attachment-ready-burn-rate
- alert: MessengerAttachmentReadyBurnRateSlow
expr: messenger:sli_attachment_slow_ratio_1m > (6 * 0.01) and messenger:sli_attachment_slow_ratio_5m > (6 * 0.01) and sum(rate(messenger_attachment_ready_duration_seconds_count[1m])) > 0
for: 20s
labels:
severity: ticket
slo: attachment-ready
burn_rate: slow
annotations:
summary: Attachment ready latency consumes its error budget persistently
description: More than 6% of completed attachments exceed 10s in both windows.
runbook: infrastructure/telemetry/runbooks/level5.md#attachment-ready-burn-rate
@@ -0,0 +1,25 @@
# Runbook уровня 4
## API high error rate
1. Сравнить error ratio с RPS на dashboard.
2. Найти в Loki `{service_name="messenger-api"} | status_class="5xx"`.
3. Открыть `trace_id` в Tempo.
4. Ошибочный `postgresql.*` client span указывает на БД; медленный server span без медленного DB child — на handler/внешнюю зависимость.
5. Проверить DB pool used/capacity и rate waits.
6. После восстановления создать успешные запросы и дождаться `resolved`.
## Queue lag growing
1. Сравнить `messenger_queue_depth` и `messenger_queue_oldest_job_age_seconds`.
2. Проверить worker busy/capacity и `attachment_job_failed` в Loki.
3. Открыть consumer trace и S3/PostgreSQL child spans.
4. Восстановить worker; depth/age должны вернуться к нулю, alert — в `resolved`.
## Telemetry backend unavailable
1. Проверить `otelcol_exporter_queue_size`, capacity и failure counters.
2. Memory limiter — 192 MiB при container limit 256 MiB; exporter queues — 256 batches.
3. API/очередь не зависят от Loki/Tempo. После 30 s retry telemetry может отбрасываться — это bounded degradation.
4. После восстановления backend проверить уменьшение очереди и появление новых сигналов.
@@ -0,0 +1,32 @@
# Runbook уровня 5: SLO burn rate
## SLO и приоритет
- Policy window — 7 дней, что совпадает с retention Prometheus.
- API availability SLO: не менее 99% HTTP-запросов без 5xx (`messenger:slo_api_success_ratio_7d`).
- Attachment ready SLO: не менее 99% успешно завершённых attachments переходят в `ready` не позднее 10 секунд после durable acceptance (`messenger:slo_attachment_ready_ratio_7d`).
- `fast` (14.4x, 30s + 2m) — page: бюджет расходуется достаточно быстро для немедленного вмешательства.
- `slow` (6x, 1m + 5m) — ticket: деградация устойчивее, но допускает более спокойную диагностику.
- Оба окна должны нарушаться одновременно. Traffic guard исключает алерт при отсутствии наблюдений.
## API burn rate
1. В Prometheus открыть `ALERTS{alertname=~"MessengerAPIBurnRate(Fast|Slow)"}` и записать `activeAt`.
2. Сравнить `messenger:sli_api_error_ratio_30s`, `_1m`, `_2m`, `_5m` и RPS. Одно короткое окно без длинного не считается burn-rate инцидентом.
3. В Loki выполнить `{service_name="messenger-api"} | status_class="5xx"` и взять свежие `request_id`/`trace_id`.
4. Открыть trace в Tempo. `postgresql.acquire` error означает исчерпание/недоступность pool; `postgresql.*` query error — ошибку операции; медленный server span без DB/S3 child указывает на handler.
5. Проверить `messenger_db_pool_connections`, `messenger_db_pool_waits_total`, process RAM/CPU и health зависимостей.
6. Восстановить зависимость, создать контрольные успешные запросы. Зафиксировать момент исчезновения alert и recovery time.
## Attachment ready burn rate
1. Сравнить `messenger:sli_attachment_slow_ratio_30s`, `_1m`, `_2m`, `_5m` с queue depth/oldest age.
2. Проверить `messenger_worker_busy / messenger_worker_capacity`; saturation около 1 при растущей очереди означает недостаточную worker capacity.
3. Найти `attachment_job_failed`/`attachment_job_completed` в Loki и перейти по trace ID к producer/consumer spans.
4. Ошибка `s3.*` указывает на object storage; `postgresql.*` — на DB; длинный разрыв между producer и consumer — на queue/worker.
5. Восстановить worker/backend. Убедиться, что новые attachments укладываются в 10 секунд, оба burn-rate alert исчезли, queue age вернулся к нулю.
## Проверка ложного срабатывания
`tests/slo_burn_rate.py` сначала создаёт большой успешный baseline, затем короткий ограниченный 5xx burst. В течение observation window ни `Fast`, ни `Slow` не должны перейти в `pending` или `firing`. Далее тот же тест создаёт длительную DB-деградацию и измеряет detection/recovery. Это отделяет чувствительность к реальному расходованию бюджета от реакции на единичную ошибку.
@@ -0,0 +1,22 @@
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
compactor:
compaction:
block_retention: 168h
+193
View File
@@ -0,0 +1,193 @@
package broker
import (
"context"
"encoding/json"
"fmt"
neturl "net/url"
"os"
"sync"
"time"
"mtusi2026lab7/internal/domain"
"mtusi2026lab7/internal/security"
amqp "github.com/rabbitmq/amqp091-go"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)
const QueueName = "attachment.process.v1"
type RabbitMQ struct {
connection *amqp.Connection
channel *amqp.Channel
confirms <-chan amqp.Confirmation
publishMu sync.Mutex
}
func Open(url string, prefetch int) (*RabbitMQ, error) {
if url == "" {
return nil, fmt.Errorf("broker URL is required")
}
parsedURL, err := neturl.Parse(url)
if err != nil {
return nil, fmt.Errorf("parse broker URL: %w", err)
}
connectionConfig := amqp.Config{Heartbeat: 10 * time.Second, Locale: "en_US"}
if parsedURL.Scheme == "amqps" {
serverName := os.Getenv("BROKER_TLS_SERVER_NAME")
if serverName == "" {
serverName = "dependency-gateway"
}
connectionConfig.TLSClientConfig, err = security.ClientMTLSConfig(
os.Getenv("CLIENT_TLS_CA_FILE"),
os.Getenv("CLIENT_TLS_CERT_FILE"),
os.Getenv("CLIENT_TLS_KEY_FILE"),
serverName,
)
if err != nil {
return nil, fmt.Errorf("configure broker mTLS: %w", err)
}
}
connection, err := amqp.DialConfig(url, connectionConfig)
if err != nil {
return nil, fmt.Errorf("connect RabbitMQ: %w", err)
}
channel, err := connection.Channel()
if err != nil {
_ = connection.Close()
return nil, fmt.Errorf("open RabbitMQ channel: %w", err)
}
if _, err = channel.QueueDeclare(QueueName, true, false, false, false, nil); err != nil {
_ = channel.Close()
_ = connection.Close()
return nil, fmt.Errorf("declare RabbitMQ queue: %w", err)
}
if prefetch > 0 {
if err = channel.Qos(prefetch, 0, false); err != nil {
_ = channel.Close()
_ = connection.Close()
return nil, fmt.Errorf("set RabbitMQ prefetch: %w", err)
}
}
client := &RabbitMQ{connection: connection, channel: channel}
if err = channel.Confirm(false); err != nil {
client.Close()
return nil, fmt.Errorf("enable RabbitMQ publisher confirms: %w", err)
}
client.confirms = channel.NotifyPublish(make(chan amqp.Confirmation, 1))
return client, nil
}
func (client *RabbitMQ) Publish(ctx context.Context, job domain.AttachmentJob) (err error) {
parentCarrier := propagation.MapCarrier{}
if job.TraceParent != "" {
parentCarrier.Set("traceparent", job.TraceParent)
}
if job.TraceState != "" {
parentCarrier.Set("tracestate", job.TraceState)
}
ctx = otel.GetTextMapPropagator().Extract(ctx, parentCarrier)
ctx, span := otel.Tracer("mtusi2026lab7/broker").Start(
ctx,
QueueName+" publish",
trace.WithSpanKind(trace.SpanKindProducer),
trace.WithAttributes(
attribute.String("messaging.system", "rabbitmq"),
attribute.String("messaging.destination.name", QueueName),
attribute.String("messaging.operation.name", "publish"),
attribute.Int("job.attempt", job.Attempt),
),
)
defer func() {
if err != nil {
span.SetStatus(codes.Error, "broker publish failed")
} else {
span.SetStatus(codes.Ok, "")
}
span.End()
}()
body, err := json.Marshal(job.Message())
if err != nil {
return fmt.Errorf("encode attachment job: %w", err)
}
traceCarrier := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, traceCarrier)
headers := amqp.Table{}
for _, key := range traceCarrier.Keys() {
headers[key] = traceCarrier.Get(key)
}
client.publishMu.Lock()
defer client.publishMu.Unlock()
if err = client.channel.PublishWithContext(ctx, "", QueueName, false, false, amqp.Publishing{
DeliveryMode: amqp.Persistent,
ContentType: "application/json",
Type: domain.AttachmentJobType,
MessageId: job.JobID,
Timestamp: time.Now().UTC(),
Headers: headers,
Body: body,
}); err != nil {
return fmt.Errorf("publish attachment job: %w", err)
}
select {
case confirmation, ok := <-client.confirms:
if !ok {
return fmt.Errorf("publisher confirm channel closed")
}
if !confirmation.Ack {
return fmt.Errorf("broker rejected attachment job")
}
return nil
case <-ctx.Done():
return fmt.Errorf("wait for publisher confirm: %w", ctx.Err())
}
}
func ContextFromDelivery(ctx context.Context, delivery amqp.Delivery) context.Context {
carrier := propagation.MapCarrier{}
for key, value := range delivery.Headers {
if text, ok := value.(string); ok {
carrier.Set(key, text)
}
}
return otel.GetTextMapPropagator().Extract(ctx, carrier)
}
func (client *RabbitMQ) Consume(consumerName string) (<-chan amqp.Delivery, error) {
deliveries, err := client.channel.Consume(QueueName, consumerName, false, false, false, false, nil)
if err != nil {
return nil, fmt.Errorf("consume attachment jobs: %w", err)
}
return deliveries, nil
}
func Decode(delivery amqp.Delivery) (domain.AttachmentJobMessage, error) {
var message domain.AttachmentJobMessage
if err := json.Unmarshal(delivery.Body, &message); err != nil {
return message, fmt.Errorf("decode attachment job: %w", err)
}
if message.SchemaVersion != 1 || message.Type != domain.AttachmentJobType || message.JobID == "" || message.AttachmentID == "" || message.PipelineVersion < 1 || message.Attempt < 1 {
return message, fmt.Errorf("attachment job has invalid required fields")
}
return message, nil
}
func (client *RabbitMQ) Close() error {
if client == nil {
return nil
}
if client.channel != nil {
_ = client.channel.Close()
}
if client.connection != nil {
return client.connection.Close()
}
return nil
}
+110
View File
@@ -0,0 +1,110 @@
package cache
import (
"context"
"errors"
"log"
"mtusi2026lab7/internal/adapter/redis"
"mtusi2026lab7/internal/application"
"mtusi2026lab7/internal/domain"
)
// CachedRepository декорирует основной Repository. Все операции, кроме чтения
// и создания чата, автоматически делегируются встроенному Repository.
type CachedRepository struct {
application.Repository
chatCache redis.ChatCache
logger *log.Logger
}
func NewCachedRepository(
repository application.Repository,
chatCache redis.ChatCache,
logger *log.Logger,
) *CachedRepository {
if logger == nil {
logger = log.Default()
}
return &CachedRepository{
Repository: repository,
chatCache: chatCache,
logger: logger,
}
}
func (r *CachedRepository) CreateQueuedAttachment(
ctx context.Context,
attachment domain.Attachment,
job domain.AttachmentJob,
) (domain.Attachment, error) {
queueRepository, ok := r.Repository.(application.AttachmentQueueRepository)
if !ok {
return domain.Attachment{}, errors.New("attachment queue repository is not configured")
}
return queueRepository.CreateQueuedAttachment(ctx, attachment, job)
}
func (r *CachedRepository) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
) (domain.Chat, error) {
chat, err := r.Repository.CreateChat(ctx, title, memberIDs)
if err != nil {
return domain.Chat{}, err
}
// Запись в PostgreSQL уже подтверждена. Ошибка необязательного кэша не
// должна превращать успешную бизнес-операцию в 503.
if err = r.chatCache.Set(ctx, chat); err != nil {
r.logger.Printf("[WARN] Redis chat cache write failed: %v", err)
}
return chat, nil
}
func (r *CachedRepository) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
chat, err := r.chatCache.Get(ctx, chatID)
if err == nil {
if !containsMember(chat.MemberIDs, callerID) {
return domain.Chat{}, domain.ErrNotFound
}
return chat, nil
}
shouldFillCache := errors.Is(err, redis.ErrMiss)
if !shouldFillCache {
r.logger.Printf("[WARN] Redis chat cache read failed: %v", err)
}
chat, err = r.Repository.GetChatByID(ctx, chatID, callerID)
if err != nil {
return domain.Chat{}, err
}
if shouldFillCache {
if err = r.chatCache.Set(ctx, chat); err != nil {
r.logger.Printf("[WARN] Redis chat cache fill failed: %v", err)
}
}
return chat, nil
}
func containsMember(memberIDs []string, callerID string) bool {
for _, memberID := range memberIDs {
if memberID == callerID {
return true
}
}
return false
}
var _ application.Repository = (*CachedRepository)(nil)
+183
View File
@@ -0,0 +1,183 @@
package cache
import (
"context"
"errors"
"io"
"log"
"testing"
"mtusi2026lab7/internal/adapter/memory"
"mtusi2026lab7/internal/adapter/redis"
"mtusi2026lab7/internal/application"
"mtusi2026lab7/internal/domain"
)
type fakeChatCache struct {
chats map[string]domain.Chat
getErr error
setErr error
sets int
}
func (c *fakeChatCache) Get(
_ context.Context,
chatID string,
) (domain.Chat, error) {
if c.getErr != nil {
return domain.Chat{}, c.getErr
}
chat, exists := c.chats[chatID]
if !exists {
return domain.Chat{}, redis.ErrMiss
}
return chat, nil
}
func (c *fakeChatCache) Set(
_ context.Context,
chat domain.Chat,
) error {
c.sets++
if c.setErr != nil {
return c.setErr
}
c.chats[chat.ID] = chat
return nil
}
type countingRepository struct {
application.Repository
getChatCalls int
}
func (r *countingRepository) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
r.getChatCalls++
return r.Repository.GetChatByID(ctx, chatID, callerID)
}
func cachedRepositoryFixture(
t *testing.T,
) (*countingRepository, *fakeChatCache, domain.User, domain.User, domain.Chat) {
t.Helper()
legacy := memory.NewMemoryStore()
member, err := legacy.CreateUser("cache_member", "Участник")
if err != nil {
t.Fatalf("create member: %v", err)
}
outsider, err := legacy.CreateUser("cache_outsider", "Посторонний")
if err != nil {
t.Fatalf("create outsider: %v", err)
}
chat, err := legacy.CreateChat("Кешируемый чат", []string{member.ID})
if err != nil {
t.Fatalf("create chat: %v", err)
}
repository := &countingRepository{
Repository: memory.NewMemoryRepository(legacy),
}
chatCache := &fakeChatCache{
chats: make(map[string]domain.Chat),
}
return repository, chatCache, member, outsider, chat
}
func TestCachedRepositoryMissThenHit(t *testing.T) {
repository, chatCache, member, _, expected := cachedRepositoryFixture(t)
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
first, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
if err != nil {
t.Fatalf("first read: %v", err)
}
second, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
if err != nil {
t.Fatalf("second read: %v", err)
}
if repository.getChatCalls != 1 {
t.Fatalf("expected one source read, got %d", repository.getChatCalls)
}
if chatCache.sets != 1 {
t.Fatalf("expected one cache fill, got %d", chatCache.sets)
}
if first.ID != expected.ID || second.ID != expected.ID {
t.Fatal("cache changed chat identity")
}
}
func TestCachedRepositoryFallsBackWhenCacheUnavailable(t *testing.T) {
repository, chatCache, member, _, expected := cachedRepositoryFixture(t)
chatCache.getErr = errors.New("redis unavailable")
chatCache.setErr = errors.New("redis unavailable")
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
chat, err := cached.GetChatByID(context.Background(), expected.ID, member.ID)
if err != nil {
t.Fatalf("fallback read: %v", err)
}
if chat.ID != expected.ID || repository.getChatCalls != 1 {
t.Fatal("source repository was not used after cache failure")
}
if chatCache.sets != 0 {
t.Fatal("failed cache read must not trigger another cache operation")
}
}
func TestCachedRepositoryChecksMembershipOnHit(t *testing.T) {
repository, chatCache, _, outsider, expected := cachedRepositoryFixture(t)
chatCache.chats[expected.ID] = expected
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
_, err := cached.GetChatByID(context.Background(), expected.ID, outsider.ID)
if !errors.Is(err, domain.ErrNotFound) {
t.Fatalf("expected ErrNotFound for outsider, got %v", err)
}
if repository.getChatCalls != 0 {
t.Fatal("cache hit unexpectedly queried source repository")
}
}
func TestCachedRepositoryIgnoresWriteFailure(t *testing.T) {
repository, chatCache, member, _, _ := cachedRepositoryFixture(t)
chatCache.setErr = errors.New("redis unavailable")
cached := NewCachedRepository(
repository,
chatCache,
log.New(io.Discard, "", 0),
)
chat, err := cached.CreateChat(
context.Background(),
"Новый чат",
[]string{member.ID},
)
if err != nil {
t.Fatalf("create chat with unavailable cache: %v", err)
}
if chat.ID == "" || chatCache.sets != 1 {
t.Fatal("chat was not created before best-effort cache write")
}
}
+33
View File
@@ -0,0 +1,33 @@
package health
import (
"context"
"fmt"
)
type Checker interface {
Ping(ctx context.Context) error
}
type MultiChecker struct {
checkers []Checker
}
func NewMultiChecker(checkers ...Checker) *MultiChecker {
filtered := make([]Checker, 0, len(checkers))
for _, checker := range checkers {
if checker != nil {
filtered = append(filtered, checker)
}
}
return &MultiChecker{checkers: filtered}
}
func (checker *MultiChecker) Ping(ctx context.Context) error {
for index, dependency := range checker.checkers {
if err := dependency.Ping(ctx); err != nil {
return fmt.Errorf("dependency %d: %w", index, err)
}
}
return nil
}
+8
View File
@@ -0,0 +1,8 @@
package memory
import "mtusi2026lab7/internal/domain"
var (
ErrNotFound = domain.ErrNotFound
ErrConflict = domain.ErrConflict
)
+401
View File
@@ -0,0 +1,401 @@
package memory
import (
"context"
"fmt"
"sync"
"time"
"mtusi2026lab7/internal/application"
"mtusi2026lab7/internal/domain"
)
type memorySession struct {
userID string
expiresAt time.Time
}
type memoryIdempotencyScope struct {
actorID string
method string
canonicalPath string
key string
}
type memoryIdempotencyResult struct {
requestHash [32]byte
message domain.Message
expiresAt time.Time
}
type MemoryRepository struct {
legacy *MemoryStore
mu sync.RWMutex
passwordByUserID map[string]string
userIDByUsername map[string]string
sessionsByHashKey map[[32]byte]memorySession
idempotencyByScope map[memoryIdempotencyScope]memoryIdempotencyResult
}
func NewMemoryRepository(legacy *MemoryStore) *MemoryRepository {
return &MemoryRepository{
legacy: legacy,
passwordByUserID: make(map[string]string),
userIDByUsername: make(map[string]string),
sessionsByHashKey: make(map[[32]byte]memorySession),
idempotencyByScope: make(map[memoryIdempotencyScope]memoryIdempotencyResult),
}
}
func (r *MemoryRepository) CreateUser(
ctx context.Context,
username string,
displayName string,
passwordHash string,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
user, err := r.legacy.CreateUser(username, displayName)
if err != nil {
return domain.User{}, err
}
r.mu.Lock()
r.passwordByUserID[user.ID] = passwordHash
r.userIDByUsername[user.Username] = user.ID
r.mu.Unlock()
return user, nil
}
func (r *MemoryRepository) GetUserByID(
ctx context.Context,
userID string,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
return r.legacy.GetUserByID(userID)
}
func (r *MemoryRepository) GetUserByUsername(
ctx context.Context,
username string,
) (domain.User, string, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, "", err
}
r.mu.RLock()
userID, exists := r.userIDByUsername[username]
passwordHash := r.passwordByUserID[userID]
r.mu.RUnlock()
if !exists {
return domain.User{}, "", ErrNotFound
}
user, err := r.legacy.GetUserByID(userID)
if err != nil {
return domain.User{}, "", err
}
return user, passwordHash, nil
}
func (r *MemoryRepository) UpdatePasswordHash(
ctx context.Context,
userID string,
previousHash string,
newHash string,
) error {
if err := ctx.Err(); err != nil {
return err
}
r.mu.Lock()
defer r.mu.Unlock()
if current, exists := r.passwordByUserID[userID]; exists && current == previousHash {
r.passwordByUserID[userID] = newHash
}
return nil
}
func (r *MemoryRepository) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
) (domain.Chat, error) {
if err := ctx.Err(); err != nil {
return domain.Chat{}, err
}
return r.legacy.CreateChat(title, memberIDs)
}
func (r *MemoryRepository) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
if err := ctx.Err(); err != nil {
return domain.Chat{}, err
}
return r.legacy.GetChatByID(chatID, callerID)
}
func (r *MemoryRepository) GetChatsForUser(
ctx context.Context,
userID string,
limit int,
cursor *domain.ChatCursor,
) ([]domain.Chat, bool, error) {
if err := ctx.Err(); err != nil {
return nil, false, err
}
return r.legacy.GetChatsForUser(userID, limit, cursor)
}
func (r *MemoryRepository) CreateMessageIdempotently(
ctx context.Context,
write application.IdempotentMessageWrite,
) (domain.Message, error) {
if err := ctx.Err(); err != nil {
return domain.Message{}, err
}
scope := memoryIdempotencyScope{
actorID: write.ActorID,
method: write.Method,
canonicalPath: write.CanonicalPath,
key: write.Key,
}
now := time.Now().UTC()
r.mu.Lock()
defer r.mu.Unlock()
if _, err := r.legacy.GetChatByID(write.ChatID, write.ActorID); err != nil {
return domain.Message{}, err
}
for _, attachmentID := range write.AttachmentIDs {
attachment, err := r.legacy.GetAttachmentByID(attachmentID)
if err != nil || attachment.ChatID != write.ChatID {
return domain.Message{}, ErrNotFound
}
if attachment.Status != domain.AttachmentStatusReady {
return domain.Message{}, application.ErrAttachmentNotReady
}
}
if stored, exists := r.idempotencyByScope[scope]; exists {
if stored.expiresAt.After(now) {
if stored.requestHash != write.RequestHash {
return domain.Message{}, application.ErrIdempotencyConflict
}
return stored.message, nil
}
delete(r.idempotencyByScope, scope)
}
message, err := r.legacy.CreateMessage(
write.ChatID,
write.ActorID,
write.Text,
write.AttachmentIDs,
)
if err != nil {
return domain.Message{}, err
}
r.idempotencyByScope[scope] = memoryIdempotencyResult{
requestHash: write.RequestHash,
message: message,
expiresAt: now.Add(write.TTL),
}
return message, nil
}
func (r *MemoryRepository) GetMessages(
ctx context.Context,
chatID string,
callerID string,
limit int,
cursor *domain.MessageCursor,
) ([]domain.Message, bool, error) {
if err := ctx.Err(); err != nil {
return nil, false, err
}
return r.legacy.GetMessages(
chatID,
callerID,
limit,
cursor,
)
}
func (r *MemoryRepository) CreateSession(
ctx context.Context,
tokenHash []byte,
userID string,
expiresAt time.Time,
) error {
if err := ctx.Err(); err != nil {
return err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return err
}
r.mu.Lock()
r.sessionsByHashKey[key] = memorySession{
userID: userID,
expiresAt: expiresAt,
}
r.mu.Unlock()
return nil
}
func (r *MemoryRepository) GetUserBySession(
ctx context.Context,
tokenHash []byte,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return domain.User{}, ErrNotFound
}
r.mu.RLock()
session, exists := r.sessionsByHashKey[key]
r.mu.RUnlock()
if !exists || !session.expiresAt.After(time.Now().UTC()) {
return domain.User{}, ErrNotFound
}
return r.legacy.GetUserByID(session.userID)
}
func (r *MemoryRepository) DeleteSession(
ctx context.Context,
tokenHash []byte,
) error {
if err := ctx.Err(); err != nil {
return err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return err
}
r.mu.Lock()
delete(r.sessionsByHashKey, key)
r.mu.Unlock()
return nil
}
func (r *MemoryRepository) CreateQueuedAttachment(
ctx context.Context,
attachment domain.Attachment,
_ domain.AttachmentJob,
) (domain.Attachment, error) {
return r.CreateAttachment(ctx, attachment)
}
func (r *MemoryRepository) CreateAttachment(
ctx context.Context,
attachment domain.Attachment,
) (domain.Attachment, error) {
if err := ctx.Err(); err != nil {
return domain.Attachment{}, err
}
if err := r.legacy.PutAttachment(attachment); err != nil {
return domain.Attachment{}, err
}
return attachment, nil
}
func (r *MemoryRepository) MarkAttachmentReady(
ctx context.Context,
attachmentID string,
updatedAt time.Time,
) (domain.Attachment, error) {
if err := ctx.Err(); err != nil {
return domain.Attachment{}, err
}
return r.legacy.UpdateAttachmentStatus(
attachmentID,
domain.AttachmentStatusReady,
nil,
updatedAt,
)
}
func (r *MemoryRepository) MarkAttachmentFailed(
ctx context.Context,
attachmentID string,
errorCode string,
updatedAt time.Time,
) error {
if err := ctx.Err(); err != nil {
return err
}
_, err := r.legacy.UpdateAttachmentStatus(
attachmentID,
domain.AttachmentStatusFailed,
&errorCode,
updatedAt,
)
return err
}
func (r *MemoryRepository) GetAttachment(
ctx context.Context,
attachmentID string,
callerID string,
) (domain.Attachment, error) {
if err := ctx.Err(); err != nil {
return domain.Attachment{}, err
}
attachment, err := r.legacy.GetAttachmentByID(attachmentID)
if err != nil {
return domain.Attachment{}, err
}
if _, err = r.legacy.GetChatByID(attachment.ChatID, callerID); err != nil {
return domain.Attachment{}, err
}
if attachment.Variants == nil {
attachment.Variants = make([]domain.AttachmentVariant, 0)
}
return attachment, nil
}
func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) {
var key [32]byte
if len(tokenHash) != len(key) {
return key, fmt.Errorf(
"session token hash must contain %d bytes",
len(key),
)
}
copy(key[:], tokenHash)
return key, nil
}
var _ application.Repository = (*MemoryRepository)(nil)
+371
View File
@@ -0,0 +1,371 @@
package memory
import (
"fmt"
"sort"
"sync"
"time"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
)
type MemoryStore struct {
mu sync.RWMutex
usersByID map[string]domain.User //key = user UUID
usersByUsername map[string]string //key = username для быстрой проверки уникальности
chatsByID map[string]domain.Chat //key = chat UUID
messagesByChatID map[string][]domain.Message // key = chat UUID, value = слайс сообщений
attachmentsByID map[string]domain.Attachment
}
func NewMemoryStore() *MemoryStore {
return &MemoryStore{
usersByID: make(map[string]domain.User),
usersByUsername: make(map[string]string),
chatsByID: make(map[string]domain.Chat),
messagesByChatID: make(map[string][]domain.Message),
attachmentsByID: make(map[string]domain.Attachment),
}
}
// ---пользователи---
func (s *MemoryStore) CreateUser(username, displayName string) (domain.User, error) {
s.mu.Lock()
defer s.mu.Unlock()
// дубликат username -> 409 Conflict
if _, exists := s.usersByUsername[username]; exists {
return domain.User{}, ErrConflict
}
user := domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
CreatedAt: time.Now().UTC(),
}
s.usersByID[user.ID] = user
s.usersByUsername[user.Username] = user.ID
return user, nil
}
func (s *MemoryStore) GetUserByID(id string) (domain.User, error) {
s.mu.RLock()
defer s.mu.RUnlock()
user, exists := s.usersByID[id]
if !exists {
return domain.User{}, ErrNotFound
}
return user, nil
}
// ---чаты---
func (s *MemoryStore) CreateChat(title string, memberIDs []string) (domain.Chat, error) {
s.mu.Lock()
defer s.mu.Unlock()
//все участники рил существуют
for _, memberID := range memberIDs {
if _, exists := s.usersByID[memberID]; !exists {
return domain.Chat{}, fmt.Errorf(
"%w: member %s",
ErrNotFound,
memberID,
)
}
}
chat := domain.Chat{
ID: uuid.NewString(),
Title: title,
MemberIDs: append([]string(nil), memberIDs...), //копирую слайс для изоляции
CreatedAt: time.Now().UTC(),
}
s.chatsByID[chat.ID] = chat
s.messagesByChatID[chat.ID] = make([]domain.Message, 0)
return chat, nil
}
func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error) {
s.mu.RLock()
defer s.mu.RUnlock()
chat, exists := s.chatsByID[chatID]
if !exists {
return domain.Chat{}, ErrNotFound
}
// Требование безопасности: посторонний получает 404, а не 403
isMember := false
for _, m := range chat.MemberIDs {
if m == callerID {
isMember = true
break
}
}
if !isMember {
return domain.Chat{}, ErrNotFound
}
return chat, nil
}
func (s *MemoryStore) GetChatsForUser(
userID string,
limit int,
cursorData *domain.ChatCursor,
) ([]domain.Chat, bool, error) {
s.mu.RLock()
defer s.mu.RUnlock()
chats := make([]domain.Chat, 0)
for _, chat := range s.chatsByID {
for _, memberID := range chat.MemberIDs {
if memberID == userID {
chats = append(chats, chat)
break
}
}
}
sort.Slice(chats, func(i, j int) bool {
if chats[i].CreatedAt.Equal(chats[j].CreatedAt) {
return chats[i].ID < chats[j].ID
}
return chats[i].CreatedAt.Before(chats[j].CreatedAt)
})
start := 0
if cursorData != nil {
start = sort.Search(len(chats), func(index int) bool {
chat := chats[index]
if chat.CreatedAt.After(cursorData.CreatedAt) {
return true
}
return chat.CreatedAt.Equal(cursorData.CreatedAt) &&
chat.ID > cursorData.ChatID
})
}
if start >= len(chats) {
return make([]domain.Chat, 0), false, nil
}
end := start + limit
if end > len(chats) {
end = len(chats)
}
items := make([]domain.Chat, end-start)
copy(items, chats[start:end])
return items, end < len(chats), nil
}
// PutAttachment stores metadata for adapter and application tests. Binary
// content intentionally does not belong to this in-memory metadata store.
func (s *MemoryStore) PutAttachment(attachment domain.Attachment) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, exists := s.attachmentsByID[attachment.ID]; exists {
return ErrConflict
}
chat, exists := s.chatsByID[attachment.ChatID]
if !exists {
return ErrNotFound
}
ownerIsMember := false
for _, memberID := range chat.MemberIDs {
if memberID == attachment.OwnerID {
ownerIsMember = true
break
}
}
if !ownerIsMember {
return ErrNotFound
}
s.attachmentsByID[attachment.ID] = attachment
return nil
}
func (s *MemoryStore) GetAttachmentByID(
attachmentID string,
) (domain.Attachment, error) {
s.mu.RLock()
defer s.mu.RUnlock()
attachment, exists := s.attachmentsByID[attachmentID]
if !exists {
return domain.Attachment{}, ErrNotFound
}
return attachment, nil
}
func (s *MemoryStore) UpdateAttachmentStatus(
attachmentID string,
status domain.AttachmentStatus,
errorCode *string,
updatedAt time.Time,
) (domain.Attachment, error) {
s.mu.Lock()
defer s.mu.Unlock()
attachment, exists := s.attachmentsByID[attachmentID]
if !exists {
return domain.Attachment{}, ErrNotFound
}
if attachment.Status != domain.AttachmentStatusPending {
return domain.Attachment{}, ErrConflict
}
attachment.Status = status
attachment.ErrorCode = errorCode
attachment.UpdatedAt = updatedAt
if attachment.Variants == nil {
attachment.Variants = make([]domain.AttachmentVariant, 0)
}
s.attachmentsByID[attachmentID] = attachment
return attachment, nil
}
// ---Сообщения---
func (s *MemoryStore) CreateMessage(
chatID, senderID, text string,
attachmentLists ...[]string,
) (domain.Message, error) {
messageID := uuid.NewString()
attachmentIDs := make([]string, 0)
if len(attachmentLists) > 0 {
attachmentIDs = append(attachmentIDs, attachmentLists[0]...)
}
s.mu.Lock()
defer s.mu.Unlock()
chat, exists := s.chatsByID[chatID]
if !exists {
return domain.Message{}, ErrNotFound
}
isMember := false
for _, memberID := range chat.MemberIDs {
if memberID == senderID {
isMember = true
break
}
}
if !isMember {
return domain.Message{}, ErrNotFound
}
createdAt := time.Now().UTC()
messages := s.messagesByChatID[chatID]
if len(messages) > 0 {
lastCreatedAt := messages[len(messages)-1].CreatedAt
// Обеспечиваем строго возрастающее время внутри каждого чата.
if !createdAt.After(lastCreatedAt) {
createdAt = lastCreatedAt.Add(time.Nanosecond)
}
}
message := domain.Message{
ID: messageID,
ChatID: chatID,
SenderID: senderID,
Text: text,
AttachmentIDs: attachmentIDs,
CreatedAt: createdAt,
}
s.messagesByChatID[chatID] = append(messages, message)
return message, nil
}
func (s *MemoryStore) GetMessages(
chatID, callerID string,
limit int,
cursorData *domain.MessageCursor,
) ([]domain.Message, bool, error) {
s.mu.RLock()
defer s.mu.RUnlock()
chat, exists := s.chatsByID[chatID]
if !exists {
return nil, false, ErrNotFound
}
isMember := false
for _, memberID := range chat.MemberIDs {
if memberID == callerID {
isMember = true
break
}
}
if !isMember {
return nil, false, ErrNotFound
}
messages := s.messagesByChatID[chatID]
start := 0
if cursorData != nil {
// Срез уже упорядочен во время записи, поэтому вместо
// полного прохода используем бинарный поиск.
start = sort.Search(len(messages), func(index int) bool {
message := messages[index]
if message.CreatedAt.After(cursorData.CreatedAt) {
return true
}
return message.CreatedAt.Equal(cursorData.CreatedAt) &&
message.ID > cursorData.MessageID
})
}
if start >= len(messages) {
return make([]domain.Message, 0), false, nil
}
end := len(messages)
if limit > 0 && end-start > limit {
end = start + limit
}
// копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез
items := make([]domain.Message, end-start)
for index, message := range messages[start:end] {
message.AttachmentIDs = append(
make([]string, 0, len(message.AttachmentIDs)),
message.AttachmentIDs...,
)
items[index] = message
}
return items, end < len(messages), nil
}
+226
View File
@@ -0,0 +1,226 @@
package objectstore
import (
"bytes"
"context"
"fmt"
"io"
"net/url"
"strings"
"time"
"mtusi2026lab7/internal/application"
minio "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
type MinIOStore struct {
client *minio.Client
bucket string
operationTimeout time.Duration
}
type StoredObject struct {
Key string
SizeBytes int64
LastModified time.Time
}
func NewMinIOStore(
endpoint string,
region string,
bucket string,
accessKeyID string,
secretAccessKey string,
operationTimeout time.Duration,
) (*MinIOStore, error) {
parsedEndpoint, err := url.Parse(endpoint)
if err != nil || parsedEndpoint.Host == "" {
return nil, fmt.Errorf("S3 endpoint must be an absolute HTTP(S) URL")
}
if parsedEndpoint.Scheme != "http" && parsedEndpoint.Scheme != "https" {
return nil, fmt.Errorf("S3 endpoint scheme must be http or https")
}
if parsedEndpoint.Path != "" && parsedEndpoint.Path != "/" {
return nil, fmt.Errorf("S3 endpoint must not contain a path")
}
if parsedEndpoint.RawQuery != "" || parsedEndpoint.Fragment != "" || parsedEndpoint.User != nil {
return nil, fmt.Errorf("S3 endpoint must not contain credentials, query or fragment")
}
if strings.TrimSpace(bucket) == "" || strings.TrimSpace(accessKeyID) == "" ||
strings.TrimSpace(secretAccessKey) == "" {
return nil, fmt.Errorf("S3 bucket and credentials are required")
}
if operationTimeout <= 0 {
return nil, fmt.Errorf("S3 operation timeout must be positive")
}
client, err := minio.New(parsedEndpoint.Host, &minio.Options{
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
Secure: parsedEndpoint.Scheme == "https",
Region: region,
})
if err != nil {
return nil, fmt.Errorf("create MinIO client: %w", err)
}
return &MinIOStore{client: client, bucket: bucket, operationTimeout: operationTimeout}, nil
}
func (store *MinIOStore) Put(ctx context.Context, object application.ObjectPut) error {
ctx, span := startObjectSpan(ctx, "put")
defer span.End()
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
defer cancel()
upload, err := store.client.PutObject(
operationContext,
store.bucket,
object.Key,
object.Body,
object.SizeBytes,
minio.PutObjectOptions{ContentType: object.ContentType},
)
if err != nil {
return fmt.Errorf("put MinIO object: %w", err)
}
if upload.Size != object.SizeBytes {
return fmt.Errorf("put MinIO object: stored %d bytes, want %d", upload.Size, object.SizeBytes)
}
return nil
}
func (store *MinIOStore) Get(
ctx context.Context,
key string,
) (application.ObjectContent, error) {
ctx, span := startObjectSpan(ctx, "get")
defer span.End()
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
stat, err := store.client.StatObject(
operationContext,
store.bucket,
key,
minio.StatObjectOptions{},
)
if err != nil {
cancel()
return application.ObjectContent{}, fmt.Errorf("stat MinIO object: %w", err)
}
object, err := store.client.GetObject(
operationContext,
store.bucket,
key,
minio.GetObjectOptions{},
)
if err != nil {
cancel()
return application.ObjectContent{}, fmt.Errorf("get MinIO object: %w", err)
}
firstByte := make([]byte, 1)
readCount, readError := object.Read(firstByte)
if readError != nil && readCount == 0 {
_ = object.Close()
cancel()
return application.ObjectContent{}, fmt.Errorf("read MinIO object: %w", readError)
}
if readCount != 1 {
_ = object.Close()
cancel()
return application.ObjectContent{}, fmt.Errorf("read MinIO object: expected non-empty object")
}
return application.ObjectContent{
Body: &cancelingReadCloser{
Reader: io.MultiReader(bytes.NewReader(firstByte), object),
Closer: object,
cancel: cancel,
},
SizeBytes: stat.Size,
}, nil
}
func (store *MinIOStore) List(
ctx context.Context,
prefix string,
) ([]StoredObject, error) {
ctx, span := startObjectSpan(ctx, "list")
defer span.End()
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
defer cancel()
objects := make([]StoredObject, 0)
for object := range store.client.ListObjects(
operationContext,
store.bucket,
minio.ListObjectsOptions{Prefix: prefix, Recursive: true},
) {
if object.Err != nil {
return nil, fmt.Errorf("list MinIO objects: %w", object.Err)
}
objects = append(objects, StoredObject{
Key: object.Key,
SizeBytes: object.Size,
LastModified: object.LastModified.UTC(),
})
}
return objects, nil
}
func (store *MinIOStore) Delete(ctx context.Context, key string) error {
ctx, span := startObjectSpan(ctx, "delete")
defer span.End()
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
defer cancel()
if err := store.client.RemoveObject(
operationContext,
store.bucket,
key,
minio.RemoveObjectOptions{},
); err != nil {
return fmt.Errorf("delete MinIO object: %w", err)
}
return nil
}
func (store *MinIOStore) Ping(ctx context.Context) error {
ctx, span := startObjectSpan(ctx, "bucket_exists")
defer span.End()
operationContext, cancel := context.WithTimeout(ctx, store.operationTimeout)
defer cancel()
exists, err := store.client.BucketExists(operationContext, store.bucket)
if err != nil {
return fmt.Errorf("check MinIO bucket: %w", err)
}
if !exists {
return fmt.Errorf("MinIO bucket %q does not exist", store.bucket)
}
return nil
}
func startObjectSpan(ctx context.Context, operation string) (context.Context, trace.Span) {
return otel.Tracer("mtusi2026lab7/s3").Start(
ctx,
"s3."+operation,
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
attribute.String("storage.system", "s3"),
attribute.String("storage.operation", operation),
),
)
}
type cancelingReadCloser struct {
io.Reader
io.Closer
cancel context.CancelFunc
}
func (reader *cancelingReadCloser) Close() error {
err := reader.Closer.Close()
reader.cancel()
return err
}
var _ application.ObjectStore = (*MinIOStore)(nil)
@@ -0,0 +1,37 @@
package objectstore
import (
"testing"
"time"
)
func TestNewMinIOStoreValidatesConfiguration(t *testing.T) {
testCases := []struct {
name string
endpoint string
bucket string
accessKey string
secretKey string
timeout time.Duration
wantError bool
}{
{name: "valid HTTP", endpoint: "http://minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second},
{name: "valid HTTPS", endpoint: "https://s3.example.test", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second},
{name: "relative endpoint", endpoint: "minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
{name: "endpoint path", endpoint: "http://minio:9000/path", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
{name: "embedded credentials", endpoint: "http://user:pass@minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
{name: "empty bucket", endpoint: "http://minio:9000", accessKey: "api", secretKey: "secret", timeout: time.Second, wantError: true},
{name: "empty credentials", endpoint: "http://minio:9000", bucket: "attachments", timeout: time.Second, wantError: true},
{name: "invalid timeout", endpoint: "http://minio:9000", bucket: "attachments", accessKey: "api", secretKey: "secret", wantError: true},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
_, err := NewMinIOStore(testCase.endpoint, "us-east-1", testCase.bucket,
testCase.accessKey, testCase.secretKey, testCase.timeout)
if (err != nil) != testCase.wantError {
t.Fatalf("NewMinIOStore() error = %v, wantError %v", err, testCase.wantError)
}
})
}
}
@@ -0,0 +1,906 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"mtusi2026lab7/internal/domain"
"github.com/jackc/pgx/v5"
)
const attachmentJobColumns = `
schema_version, job_id::text, job_type, attachment_id::text,
pipeline_version, attempt, max_attempts, status, error_code,
available_at, lease_until, leased_by, replay_count, created_at, updated_at,
COALESCE(traceparent, ''), COALESCE(tracestate, '')
`
type scanner interface {
Scan(dest ...any) error
}
func scanAttachmentJob(row scanner, job *domain.AttachmentJob) error {
return row.Scan(
&job.SchemaVersion,
&job.JobID,
&job.Type,
&job.AttachmentID,
&job.PipelineVersion,
&job.Attempt,
&job.MaxAttempts,
&job.Status,
&job.ErrorCode,
&job.AvailableAt,
&job.LeaseUntil,
&job.LeasedBy,
&job.ReplayCount,
&job.CreatedAt,
&job.UpdatedAt,
&job.TraceParent,
&job.TraceState,
)
}
func (s *PostgreSQLStore) CreateQueuedAttachment(ctx context.Context, attachment domain.Attachment, job domain.AttachmentJob) (domain.Attachment, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return domain.Attachment{}, fmt.Errorf("begin queued attachment transaction: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
err = tx.QueryRow(queryContext, `
INSERT INTO attachments (
id, chat_id, owner_id, object_key, staging_key, filename, content_type,
size_bytes, sha256, width, height, pipeline_version, status, error_code,
created_at, updated_at
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,decode($9,'hex'),$10,$11,$12,$13,NULL,$14,$15)
RETURNING created_at, updated_at
`, attachment.ID, attachment.ChatID, attachment.OwnerID, attachment.ObjectKey,
attachment.StagingKey, attachment.Filename, attachment.ContentType, attachment.SizeBytes,
attachment.SHA256, attachment.Width, attachment.Height, attachment.PipelineVersion,
attachment.Status, attachment.CreatedAt, attachment.UpdatedAt,
).Scan(&attachment.CreatedAt, &attachment.UpdatedAt)
if err != nil {
return domain.Attachment{}, fmt.Errorf("insert queued attachment: %w", err)
}
if job.AvailableAt.IsZero() {
job.AvailableAt = job.CreatedAt
}
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_jobs (
job_id, attachment_id, schema_version, job_type, pipeline_version,
attempt, max_attempts, status, available_at, created_at, updated_at,
traceparent, tracestate
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
`, job.JobID, job.AttachmentID, job.SchemaVersion, job.Type, job.PipelineVersion,
job.Attempt, job.MaxAttempts, job.Status, job.AvailableAt, job.CreatedAt, job.UpdatedAt,
job.TraceParent, job.TraceState)
if err != nil {
return domain.Attachment{}, fmt.Errorf("insert attachment job: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return domain.Attachment{}, fmt.Errorf("commit queued attachment: %w", err)
}
attachment.Variants = make([]domain.AttachmentVariant, 0)
return attachment, nil
}
func (s *PostgreSQLStore) ListUnpublishedAttachmentJobs(ctx context.Context, limit int) ([]domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs
WHERE status = 'queued' AND published_at IS NULL
AND available_at <= CURRENT_TIMESTAMP
ORDER BY available_at, created_at, job_id
LIMIT $1
`, limit)
if err != nil {
return nil, fmt.Errorf("list unpublished attachment jobs: %w", err)
}
defer rows.Close()
jobs := make([]domain.AttachmentJob, 0)
for rows.Next() {
var job domain.AttachmentJob
if err = scanAttachmentJob(rows, &job); err != nil {
return nil, fmt.Errorf("scan unpublished attachment job: %w", err)
}
jobs = append(jobs, job)
}
return jobs, rows.Err()
}
func (s *PostgreSQLStore) MarkAttachmentJobPublished(ctx context.Context, jobID string, attempt int, publishedAt time.Time) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(queryContext, `
UPDATE attachment_jobs SET published_at = $3, updated_at = $3
WHERE job_id = $1 AND attempt = $2 AND status = 'queued'
`, jobID, attempt, publishedAt)
if err != nil {
return fmt.Errorf("mark attachment job published: %w", err)
}
return nil
}
func (s *PostgreSQLStore) ClaimAttachmentJob(
ctx context.Context,
message domain.AttachmentJobMessage,
workerID string,
leaseUntil time.Time,
) (domain.AttachmentJob, bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("begin claim attachment job: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
var job domain.AttachmentJob
err = scanAttachmentJob(tx.QueryRow(queryContext, `
UPDATE attachment_jobs
SET status = 'processing', lease_until = $5, leased_by = $6,
updated_at = CURRENT_TIMESTAMP
WHERE job_id = $1 AND attachment_id = $2 AND pipeline_version = $3
AND attempt = $4 AND status = 'queued'
AND available_at <= CURRENT_TIMESTAMP
AND EXISTS (
SELECT 1 FROM attachments a
WHERE a.id = attachment_jobs.attachment_id
AND a.pipeline_version = attachment_jobs.pipeline_version
AND a.status = 'queued'
)
RETURNING `+attachmentJobColumns+`
`, message.JobID, message.AttachmentID, message.PipelineVersion, message.Attempt,
leaseUntil, workerID), &job)
if errors.Is(err, pgx.ErrNoRows) {
var status domain.AttachmentJobStatus
var attachmentStatus domain.AttachmentStatus
var attempt, activeVersion, jobVersion int
lookupErr := tx.QueryRow(queryContext, `
SELECT j.status, j.attempt, a.status, a.pipeline_version, j.pipeline_version
FROM attachment_jobs j
JOIN attachments a ON a.id=j.attachment_id
WHERE j.job_id=$1
FOR UPDATE OF a,j
`, message.JobID).Scan(
&status,
&attempt,
&attachmentStatus,
&activeVersion,
&jobVersion,
)
if errors.Is(lookupErr, pgx.ErrNoRows) {
return domain.AttachmentJob{}, false, ErrNotFound
}
if lookupErr != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("inspect unclaimed attachment job: %w", lookupErr)
}
err = nil
switch {
case status == domain.AttachmentJobQueued &&
activeVersion == jobVersion &&
attachmentStatus == domain.AttachmentStatusReady:
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='succeeded', error_code=NULL, published_at=COALESCE(published_at,CURRENT_TIMESTAMP),
lease_until=NULL, leased_by=NULL, updated_at=CURRENT_TIMESTAMP
WHERE job_id=$1
`, message.JobID)
status = domain.AttachmentJobSucceeded
case status == domain.AttachmentJobQueued && activeVersion != jobVersion:
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='superseded', error_code='superseded_pipeline',
lease_until=NULL, leased_by=NULL, updated_at=CURRENT_TIMESTAMP
WHERE job_id=$1
`, message.JobID)
status = domain.AttachmentJobSuperseded
}
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("normalize unclaimed attachment job: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("commit unclaimed attachment job: %w", err)
}
return domain.AttachmentJob{JobID: message.JobID, Status: status, Attempt: attempt}, false, nil
}
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("claim attachment job: %w", err)
}
_, err = tx.Exec(queryContext, `
UPDATE attachments SET status = 'processing', updated_at = CURRENT_TIMESTAMP
WHERE id = $1 AND pipeline_version = $2 AND status = 'queued'
`, message.AttachmentID, message.PipelineVersion)
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("mark attachment processing: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("commit claimed attachment job: %w", err)
}
return job, true, nil
}
func (s *PostgreSQLStore) GetAttachmentForProcessing(ctx context.Context, attachmentID string) (domain.Attachment, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var attachment domain.Attachment
var digest []byte
var stagingKey *string
err := s.pool.QueryRow(queryContext, `
SELECT id::text, chat_id::text, owner_id::text, object_key, staging_key,
filename, content_type, size_bytes, sha256, width, height,
pipeline_version, status, error_code, created_at, updated_at
FROM attachments WHERE id = $1
`, attachmentID).Scan(&attachment.ID, &attachment.ChatID, &attachment.OwnerID,
&attachment.ObjectKey, &stagingKey, &attachment.Filename,
&attachment.ContentType, &attachment.SizeBytes, &digest, &attachment.Width,
&attachment.Height, &attachment.PipelineVersion, &attachment.Status,
&attachment.ErrorCode, &attachment.CreatedAt, &attachment.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return domain.Attachment{}, ErrNotFound
}
if err != nil {
return domain.Attachment{}, fmt.Errorf("get attachment for processing: %w", err)
}
attachment.SHA256 = fmt.Sprintf("%x", digest)
if stagingKey != nil {
attachment.StagingKey = *stagingKey
}
return attachment, nil
}
func (s *PostgreSQLStore) CompleteAttachmentJob(
ctx context.Context,
job domain.AttachmentJob,
variants []domain.AttachmentVariant,
updatedAt time.Time,
) (bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return false, fmt.Errorf("begin complete attachment job: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
var attachmentStatus domain.AttachmentStatus
var pipelineVersion int
var jobStatus domain.AttachmentJobStatus
err = tx.QueryRow(queryContext, `
SELECT a.status, a.pipeline_version, j.status
FROM attachments a
JOIN attachment_jobs j ON j.attachment_id = a.id
WHERE a.id = $1 AND j.job_id = $2
FOR UPDATE OF a, j
`, job.AttachmentID, job.JobID).Scan(&attachmentStatus, &pipelineVersion, &jobStatus)
if err != nil {
return false, fmt.Errorf("lock attachment completion: %w", err)
}
if pipelineVersion != job.PipelineVersion || jobStatus == domain.AttachmentJobSuperseded {
if jobStatus != domain.AttachmentJobSuperseded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='superseded', error_code='superseded_pipeline',
lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, job.JobID, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
`, job.JobID, jobStatus, job.Attempt, updatedAt)
}
if err != nil {
return false, fmt.Errorf("supersede stale pipeline completion: %w", err)
}
}
if err = tx.Commit(queryContext); err != nil {
return false, fmt.Errorf("commit stale pipeline completion: %w", err)
}
return false, nil
}
if attachmentStatus == domain.AttachmentStatusReady || jobStatus == domain.AttachmentJobSucceeded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, job.JobID, updatedAt)
if err != nil {
return false, fmt.Errorf("normalize completed job: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return false, err
}
return true, nil
}
if len(variants) != 3 {
return false, fmt.Errorf("complete attachment requires three variants: %w", ErrConflict)
}
for _, variant := range variants {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, object_key, content_type,
size_bytes, width, height, sha256, created_at
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,decode($9,'hex'),$10)
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET
object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type,
size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width,
height = EXCLUDED.height, sha256 = EXCLUDED.sha256
`, job.AttachmentID, job.PipelineVersion, variant.Name, variant.ObjectKey,
variant.ContentType, variant.SizeBytes, variant.Width, variant.Height,
variant.SHA256, updatedAt)
if err != nil {
return false, fmt.Errorf("upsert attachment variant %s: %w", variant.Name, err)
}
}
tag, err := tx.Exec(queryContext, `
UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = $3
WHERE id = $1 AND pipeline_version = $2 AND status IN ('queued','processing')
`, job.AttachmentID, job.PipelineVersion, updatedAt)
if err != nil {
return false, fmt.Errorf("mark attachment ready: %w", err)
}
if tag.RowsAffected() != 1 {
return false, fmt.Errorf("active pipeline changed during completion: %w", ErrConflict)
}
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status = 'succeeded', error_code = NULL, lease_until = NULL,
leased_by = NULL, updated_at = $2
WHERE job_id = $1
`, job.JobID, updatedAt)
if err != nil {
return false, fmt.Errorf("mark attachment job succeeded: %w", err)
}
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, created_at)
VALUES ($1, 'completed', $2, 'succeeded', $3, $4)
`, job.JobID, jobStatus, job.Attempt, updatedAt)
if err != nil {
return false, fmt.Errorf("record attachment completion: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return false, fmt.Errorf("commit completed attachment job: %w", err)
}
return true, nil
}
func (s *PostgreSQLStore) RetryAttachmentJob(
ctx context.Context,
jobID string,
errorCode string,
availableAt time.Time,
updatedAt time.Time,
eventType string,
) (domain.AttachmentJob, bool, error) {
if eventType != "retry_scheduled" && eventType != "lease_recovered" {
return domain.AttachmentJob{}, false, fmt.Errorf("unsupported retry event type")
}
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("begin retry attachment job: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
var job domain.AttachmentJob
err = scanAttachmentJob(tx.QueryRow(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs WHERE job_id = $1 FOR UPDATE
`, jobID), &job)
if err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("lock attachment job for retry: %w", err)
}
var attachmentStatus domain.AttachmentStatus
var activePipelineVersion int
if err = tx.QueryRow(queryContext,
`SELECT status, pipeline_version FROM attachments WHERE id = $1 FOR UPDATE`,
job.AttachmentID,
).Scan(&attachmentStatus, &activePipelineVersion); err != nil {
return domain.AttachmentJob{}, false, fmt.Errorf("lock attachment for retry: %w", err)
}
if activePipelineVersion != job.PipelineVersion || job.Status == domain.AttachmentJobSuperseded {
previousStatus := job.Status
if job.Status != domain.AttachmentJobSuperseded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='superseded', error_code='superseded_pipeline',
lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, jobID, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
`, jobID, previousStatus, job.Attempt, updatedAt)
}
}
if err != nil {
return domain.AttachmentJob{}, false, err
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, err
}
job.Status = domain.AttachmentJobSuperseded
job.ErrorCode = stringPointer("superseded_pipeline")
job.LeaseUntil = nil
job.LeasedBy = nil
return job, true, nil
}
if attachmentStatus == domain.AttachmentStatusReady || job.Status == domain.AttachmentJobSucceeded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, jobID, updatedAt)
if err != nil {
return domain.AttachmentJob{}, false, err
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, err
}
job.Status = domain.AttachmentJobSucceeded
return job, true, nil
}
if job.Status != domain.AttachmentJobProcessing {
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, err
}
return job, job.Status == domain.AttachmentJobFailed || job.Status == domain.AttachmentJobSuperseded, nil
}
if job.Attempt >= job.MaxAttempts {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='failed', error_code=$2, lease_until=NULL, leased_by=NULL, updated_at=$3
WHERE job_id=$1
`, jobID, errorCode, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachments
SET status='failed', error_code='retry_exhausted', updated_at=$3
WHERE id=$1 AND pipeline_version=$2 AND status <> 'ready'
`, job.AttachmentID, job.PipelineVersion, updatedAt)
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, 'permanent_failure', 'processing', 'failed', $2, $3, $4)
`, jobID, job.Attempt, errorCode, updatedAt)
}
if err != nil {
return domain.AttachmentJob{}, false, err
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, err
}
job.Status = domain.AttachmentJobFailed
job.ErrorCode = &errorCode
job.LeaseUntil = nil
job.LeasedBy = nil
return job, true, nil
}
job.Attempt++
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET attempt=$2, status='queued', error_code=$3, available_at=$4,
published_at=NULL, lease_until=NULL, leased_by=NULL, updated_at=$5
WHERE job_id=$1
`, jobID, job.Attempt, errorCode, availableAt, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachments
SET status='queued', error_code=NULL, updated_at=$3
WHERE id=$1 AND pipeline_version=$2 AND status <> 'ready'
`, job.AttachmentID, job.PipelineVersion, updatedAt)
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, $2, 'processing', 'queued', $3, $4, $5)
`, jobID, eventType, job.Attempt, errorCode, updatedAt)
}
if err != nil {
return domain.AttachmentJob{}, false, err
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, false, err
}
job.Status = domain.AttachmentJobQueued
job.ErrorCode = &errorCode
job.AvailableAt = availableAt
job.LeaseUntil = nil
job.LeasedBy = nil
job.UpdatedAt = updatedAt
return job, false, nil
}
func (s *PostgreSQLStore) FailAttachmentJob(ctx context.Context, jobID, errorCode string, updatedAt time.Time) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(queryContext) }()
var attachmentID string
var attachmentStatus domain.AttachmentStatus
var activePipelineVersion, jobPipelineVersion, attempt int
var jobStatus domain.AttachmentJobStatus
err = tx.QueryRow(queryContext, `
SELECT a.id::text, a.status, a.pipeline_version, j.pipeline_version, j.status, j.attempt
FROM attachment_jobs j
JOIN attachments a ON a.id=j.attachment_id
WHERE j.job_id=$1 FOR UPDATE OF a,j
`, jobID).Scan(
&attachmentID,
&attachmentStatus,
&activePipelineVersion,
&jobPipelineVersion,
&jobStatus,
&attempt,
)
if err != nil {
return err
}
if activePipelineVersion != jobPipelineVersion || jobStatus == domain.AttachmentJobSuperseded {
if jobStatus != domain.AttachmentJobSuperseded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='superseded', error_code='superseded_pipeline',
lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, jobID, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
`, jobID, jobStatus, attempt, updatedAt)
}
}
if err != nil {
return err
}
return tx.Commit(queryContext)
}
if attachmentStatus == domain.AttachmentStatusReady || jobStatus == domain.AttachmentJobSucceeded {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
WHERE job_id=$1
`, jobID, updatedAt)
} else {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='failed', error_code=$2, lease_until=NULL, leased_by=NULL, updated_at=$3
WHERE job_id=$1
`, jobID, errorCode, updatedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachments
SET status='failed', error_code=$3, updated_at=$4
WHERE id=$1 AND pipeline_version=$2
`, attachmentID, jobPipelineVersion, errorCode, updatedAt)
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
VALUES ($1, 'permanent_failure', $2, 'failed', $3, $4, $5)
`, jobID, jobStatus, attempt, errorCode, updatedAt)
}
}
if err != nil {
return err
}
return tx.Commit(queryContext)
}
func (s *PostgreSQLStore) ListExpiredAttachmentJobs(ctx context.Context, now time.Time, limit int) ([]domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs
WHERE status='processing' AND lease_until <= $1
ORDER BY lease_until, job_id
LIMIT $2
`, now, limit)
if err != nil {
return nil, fmt.Errorf("list expired attachment jobs: %w", err)
}
defer rows.Close()
jobs := make([]domain.AttachmentJob, 0)
for rows.Next() {
var job domain.AttachmentJob
if err = scanAttachmentJob(rows, &job); err != nil {
return nil, fmt.Errorf("scan expired attachment job: %w", err)
}
jobs = append(jobs, job)
}
return jobs, rows.Err()
}
func (s *PostgreSQLStore) ReplayFailedAttachmentJob(ctx context.Context, jobID string, replayedAt time.Time) (domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("begin attachment replay: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
var job domain.AttachmentJob
err = scanAttachmentJob(tx.QueryRow(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs WHERE job_id=$1 FOR UPDATE
`, jobID), &job)
if errors.Is(err, pgx.ErrNoRows) {
return domain.AttachmentJob{}, ErrNotFound
}
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("lock failed job for replay: %w", err)
}
var attachmentStatus domain.AttachmentStatus
var activePipelineVersion int
var stagingKey *string
if err = tx.QueryRow(queryContext, `
SELECT status, staging_key, pipeline_version FROM attachments WHERE id=$1 FOR UPDATE
`, job.AttachmentID).Scan(&attachmentStatus, &stagingKey, &activePipelineVersion); err != nil {
return domain.AttachmentJob{}, err
}
if job.Status != domain.AttachmentJobFailed ||
attachmentStatus != domain.AttachmentStatusFailed ||
activePipelineVersion != job.PipelineVersion {
return domain.AttachmentJob{}, fmt.Errorf("only the active failed pipeline can be replayed: %w", ErrConflict)
}
if stagingKey == nil || *stagingKey == "" {
return domain.AttachmentJob{}, fmt.Errorf("failed job staging is no longer retained: %w", ErrConflict)
}
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET attempt=1, status='queued', error_code=NULL, available_at=$2,
published_at=NULL, lease_until=NULL, leased_by=NULL,
replay_count=replay_count+1, updated_at=$2
WHERE job_id=$1
`, jobID, replayedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachments SET status='queued', error_code=NULL, updated_at=$2 WHERE id=$1
`, job.AttachmentID, replayedAt)
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, created_at)
VALUES ($1, 'operator_replay', 'failed', 'queued', 1, $2)
`, jobID, replayedAt)
}
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("replay failed job: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, fmt.Errorf("commit attachment replay: %w", err)
}
job.Attempt = 1
job.Status = domain.AttachmentJobQueued
job.ErrorCode = nil
job.AvailableAt = replayedAt
job.ReplayCount++
job.UpdatedAt = replayedAt
return job, nil
}
func (s *PostgreSQLStore) ListFailedAttachmentJobs(ctx context.Context, limit int) ([]domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs
WHERE status='failed'
ORDER BY updated_at, job_id
LIMIT $1
`, limit)
if err != nil {
return nil, fmt.Errorf("list failed attachment jobs: %w", err)
}
defer rows.Close()
jobs := make([]domain.AttachmentJob, 0)
for rows.Next() {
var job domain.AttachmentJob
if err = scanAttachmentJob(rows, &job); err != nil {
return nil, err
}
jobs = append(jobs, job)
}
return jobs, rows.Err()
}
func (s *PostgreSQLStore) LookupAttachmentByStagingKey(
ctx context.Context,
stagingKey string,
) (string, domain.AttachmentStatus, time.Time, bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var attachmentID string
var status domain.AttachmentStatus
var updatedAt time.Time
err := s.pool.QueryRow(queryContext, `
SELECT id::text, status, updated_at FROM attachments WHERE staging_key=$1
`, stagingKey).Scan(&attachmentID, &status, &updatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", time.Time{}, false, nil
}
if err != nil {
return "", "", time.Time{}, false, err
}
return attachmentID, status, updatedAt, true, nil
}
func (s *PostgreSQLStore) ClearAttachmentStagingKey(ctx context.Context, attachmentID, stagingKey string) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(queryContext, `
UPDATE attachments SET staging_key=NULL
WHERE id=$1 AND staging_key=$2 AND status IN ('ready','failed')
`, attachmentID, stagingKey)
if err != nil {
return fmt.Errorf("clear attachment staging key: %w", err)
}
return nil
}
func (s *PostgreSQLStore) ListReadyStagingKeys(
ctx context.Context,
limit int,
) (map[string]string, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(queryContext, `
SELECT staging_key, id::text
FROM attachments
WHERE status='ready' AND staging_key IS NOT NULL
ORDER BY updated_at, id
LIMIT $1
`, limit)
if err != nil {
return nil, fmt.Errorf("list ready staging keys: %w", err)
}
defer rows.Close()
keys := make(map[string]string)
for rows.Next() {
var key, attachmentID string
if err = rows.Scan(&key, &attachmentID); err != nil {
return nil, fmt.Errorf("scan ready staging key: %w", err)
}
keys[key] = attachmentID
}
return keys, rows.Err()
}
func stringPointer(value string) *string { return &value }
func (s *PostgreSQLStore) GetAttachmentJob(ctx context.Context, jobID string) (domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var job domain.AttachmentJob
err := scanAttachmentJob(s.pool.QueryRow(queryContext, `
SELECT `+attachmentJobColumns+`
FROM attachment_jobs WHERE job_id=$1
`, jobID), &job)
if errors.Is(err, pgx.ErrNoRows) {
return domain.AttachmentJob{}, ErrNotFound
}
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("get attachment job: %w", err)
}
return job, nil
}
func (s *PostgreSQLStore) UpgradeAttachmentPipeline(
ctx context.Context,
attachmentID string,
targetVersion int,
stagingKey string,
job domain.AttachmentJob,
upgradedAt time.Time,
) (domain.AttachmentJob, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(queryContext)
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("begin pipeline upgrade: %w", err)
}
defer func() { _ = tx.Rollback(queryContext) }()
var status domain.AttachmentStatus
var currentVersion int
err = tx.QueryRow(queryContext, `
SELECT status, pipeline_version
FROM attachments WHERE id=$1 FOR UPDATE
`, attachmentID).Scan(&status, &currentVersion)
if errors.Is(err, pgx.ErrNoRows) {
return domain.AttachmentJob{}, ErrNotFound
}
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("lock attachment for pipeline upgrade: %w", err)
}
if targetVersion != currentVersion+1 ||
(status != domain.AttachmentStatusReady && status != domain.AttachmentStatusProcessing) {
return domain.AttachmentJob{}, fmt.Errorf("pipeline upgrade requires ready/processing current version and next target version: %w", ErrConflict)
}
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
SELECT job_id, 'superseded', status, 'superseded', attempt, 'superseded_pipeline', $3
FROM attachment_jobs
WHERE attachment_id=$1 AND pipeline_version < $2
AND status IN ('queued','processing')
`, attachmentID, targetVersion, upgradedAt)
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachment_jobs
SET status='superseded', error_code='superseded_pipeline',
lease_until=NULL, leased_by=NULL, updated_at=$3
WHERE attachment_id=$1 AND pipeline_version < $2
AND status IN ('queued','processing')
`, attachmentID, targetVersion, upgradedAt)
}
if err == nil {
_, err = tx.Exec(queryContext, `
UPDATE attachments
SET pipeline_version=$2, staging_key=$3, status='queued',
error_code=NULL, updated_at=$4
WHERE id=$1
`, attachmentID, targetVersion, stagingKey, upgradedAt)
}
if job.AvailableAt.IsZero() {
job.AvailableAt = upgradedAt
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_jobs (
job_id, attachment_id, schema_version, job_type, pipeline_version,
attempt, max_attempts, status, available_at, created_at, updated_at,
traceparent, tracestate
) VALUES ($1,$2,$3,$4,$5,$6,$7,'queued',$8,$9,$10,$11,$12)
`, job.JobID, attachmentID, job.SchemaVersion, job.Type, targetVersion,
job.Attempt, job.MaxAttempts, job.AvailableAt, job.CreatedAt, job.UpdatedAt,
job.TraceParent, job.TraceState)
}
if err == nil {
_, err = tx.Exec(queryContext, `
INSERT INTO attachment_job_events
(job_id, event_type, previous_status, new_status, attempt, created_at)
VALUES ($1, 'version_upgrade', 'queued', 'queued', $2, $3)
`, job.JobID, job.Attempt, upgradedAt)
}
if err != nil {
return domain.AttachmentJob{}, fmt.Errorf("apply pipeline upgrade: %w", err)
}
if err = tx.Commit(queryContext); err != nil {
return domain.AttachmentJob{}, fmt.Errorf("commit pipeline upgrade: %w", err)
}
job.Status = domain.AttachmentJobQueued
job.PipelineVersion = targetVersion
job.AvailableAt = upgradedAt
job.UpdatedAt = upgradedAt
return job, nil
}
+372
View File
@@ -0,0 +1,372 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"mtusi2026lab7/internal/domain"
"mtusi2026lab7/internal/reconcile"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateAttachment(
ctx context.Context,
attachment domain.Attachment,
) (domain.Attachment, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
err := s.pool.QueryRow(
queryContext,
`
INSERT INTO attachments (
id, chat_id, owner_id, object_key, filename, content_type,
size_bytes, sha256, width, height, status, error_code,
created_at, updated_at
)
VALUES (
$1, $2, $3, $4, $5, $6,
$7, decode($8, 'hex'), $9, $10, $11, $12,
$13, $14
)
RETURNING created_at, updated_at
`,
attachment.ID,
attachment.ChatID,
attachment.OwnerID,
attachment.ObjectKey,
attachment.Filename,
attachment.ContentType,
attachment.SizeBytes,
attachment.SHA256,
attachment.Width,
attachment.Height,
attachment.Status,
attachment.ErrorCode,
attachment.CreatedAt,
attachment.UpdatedAt,
).Scan(&attachment.CreatedAt, &attachment.UpdatedAt)
if err != nil {
return domain.Attachment{}, fmt.Errorf("insert attachment metadata: %w", err)
}
if attachment.Variants == nil {
attachment.Variants = make([]domain.AttachmentVariant, 0)
}
return attachment, nil
}
func (s *PostgreSQLStore) MarkAttachmentReady(
ctx context.Context,
attachmentID string,
updatedAt time.Time,
) (domain.Attachment, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var attachment domain.Attachment
var sha256Bytes []byte
err := s.pool.QueryRow(
queryContext,
`
UPDATE attachments
SET status = 'ready', error_code = NULL, updated_at = $2
WHERE id = $1 AND status IN ('queued', 'processing')
RETURNING
id::text, chat_id::text, owner_id::text, object_key,
filename, content_type, size_bytes, sha256, width, height,
pipeline_version, status, error_code, created_at, updated_at
`,
attachmentID,
updatedAt,
).Scan(
&attachment.ID,
&attachment.ChatID,
&attachment.OwnerID,
&attachment.ObjectKey,
&attachment.Filename,
&attachment.ContentType,
&attachment.SizeBytes,
&sha256Bytes,
&attachment.Width,
&attachment.Height,
&attachment.PipelineVersion,
&attachment.Status,
&attachment.ErrorCode,
&attachment.CreatedAt,
&attachment.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.Attachment{}, ErrConflict
}
if err != nil {
return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", err)
}
attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes)
attachment.Variants, err = s.listAttachmentVariants(queryContext, attachment.ID, attachment.PipelineVersion)
if err != nil {
return domain.Attachment{}, err
}
return attachment, nil
}
func (s *PostgreSQLStore) MarkAttachmentFailed(
ctx context.Context,
attachmentID string,
errorCode string,
updatedAt time.Time,
) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
commandTag, err := s.pool.Exec(
queryContext,
`
UPDATE attachments
SET status = 'failed', error_code = $2, updated_at = $3
WHERE id = $1 AND status IN ('queued', 'processing')
`,
attachmentID,
errorCode,
updatedAt,
)
if err != nil {
return fmt.Errorf("mark attachment failed: %w", err)
}
if commandTag.RowsAffected() != 1 {
return ErrConflict
}
return nil
}
func (s *PostgreSQLStore) GetAttachment(
ctx context.Context,
attachmentID string,
callerID string,
) (domain.Attachment, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var attachment domain.Attachment
var sha256Bytes []byte
err := s.pool.QueryRow(
queryContext,
`
SELECT
a.id::text, a.chat_id::text, a.owner_id::text, a.object_key,
a.filename, a.content_type, a.size_bytes, a.sha256,
a.width, a.height, a.pipeline_version, a.status, a.error_code,
a.created_at, a.updated_at
FROM attachments AS a
JOIN chat_members AS cm
ON cm.chat_id = a.chat_id AND cm.user_id = $2
WHERE a.id = $1
`,
attachmentID,
callerID,
).Scan(
&attachment.ID,
&attachment.ChatID,
&attachment.OwnerID,
&attachment.ObjectKey,
&attachment.Filename,
&attachment.ContentType,
&attachment.SizeBytes,
&sha256Bytes,
&attachment.Width,
&attachment.Height,
&attachment.PipelineVersion,
&attachment.Status,
&attachment.ErrorCode,
&attachment.CreatedAt,
&attachment.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.Attachment{}, ErrNotFound
}
if err != nil {
return domain.Attachment{}, fmt.Errorf("get attachment metadata: %w", err)
}
attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes)
attachment.Variants, err = s.listAttachmentVariants(queryContext, attachment.ID, attachment.PipelineVersion)
if err != nil {
return domain.Attachment{}, err
}
return attachment, nil
}
func (s *PostgreSQLStore) ListAttachmentInventory(
ctx context.Context,
) ([]reconcile.AttachmentRecord, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
rows, err := s.pool.Query(
queryContext,
`
SELECT
a.id::text,
a.object_key,
a.status,
a.updated_at,
EXISTS (
SELECT 1
FROM message_attachments AS ma
WHERE ma.attachment_id = a.id
) AS referenced,
COALESCE(a.staging_key, ''),
COALESCE(av.object_key, '')
FROM attachments AS a
LEFT JOIN attachment_variants AS av ON av.attachment_id = a.id
ORDER BY a.id, av.pipeline_version, av.name
`,
)
if err != nil {
return nil, fmt.Errorf("query attachment inventory: %w", err)
}
defer rows.Close()
records := make([]reconcile.AttachmentRecord, 0)
recordIndexes := make(map[string]int)
for rows.Next() {
var record reconcile.AttachmentRecord
var stagingKey string
var variantKey string
if err = rows.Scan(
&record.ID,
&record.ObjectKey,
&record.Status,
&record.UpdatedAt,
&record.Referenced,
&stagingKey,
&variantKey,
); err != nil {
return nil, fmt.Errorf("scan attachment inventory: %w", err)
}
if recordIndex, exists := recordIndexes[record.ID]; exists {
if variantKey != "" {
records[recordIndex].AdditionalObjectKeys = append(
records[recordIndex].AdditionalObjectKeys,
variantKey,
)
}
continue
}
if stagingKey != "" {
record.AdditionalObjectKeys = append(record.AdditionalObjectKeys, stagingKey)
}
if variantKey != "" {
record.AdditionalObjectKeys = append(record.AdditionalObjectKeys, variantKey)
}
recordIndexes[record.ID] = len(records)
records = append(records, record)
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("iterate attachment inventory: %w", err)
}
return records, nil
}
func (s *PostgreSQLStore) MarkAttachmentFailedIfUnreferenced(
ctx context.Context,
attachmentID string,
expectedStatus domain.AttachmentStatus,
updatedBefore time.Time,
errorCode string,
updatedAt time.Time,
) (bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
if err != nil {
return false, fmt.Errorf("begin attachment reconciliation transaction: %w", err)
}
defer func() { _ = transaction.Rollback(queryContext) }()
var lockedAttachmentID string
err = transaction.QueryRow(
queryContext,
`
SELECT id::text
FROM attachments
WHERE id = $1
FOR UPDATE
`,
attachmentID,
).Scan(&lockedAttachmentID)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("lock attachment during reconciliation: %w", err)
}
// This is deliberately a second statement. Under READ COMMITTED it gets a
// fresh snapshot after the row lock was acquired, so a message transaction
// that linked this attachment while we waited is visible to NOT EXISTS.
commandTag, err := transaction.Exec(
queryContext,
`
UPDATE attachments AS a
SET status = 'failed', error_code = $4, updated_at = $5
WHERE a.id = $1
AND a.status = $2
AND a.updated_at <= $3
AND NOT EXISTS (
SELECT 1
FROM message_attachments AS ma
WHERE ma.attachment_id = a.id
)
`,
attachmentID,
expectedStatus,
updatedBefore,
errorCode,
updatedAt,
)
if err != nil {
return false, fmt.Errorf("mark attachment failed during reconciliation: %w", err)
}
if err = transaction.Commit(queryContext); err != nil {
return false, fmt.Errorf("commit attachment reconciliation: %w", err)
}
return commandTag.RowsAffected() == 1, nil
}
func (s *PostgreSQLStore) listAttachmentVariants(
ctx context.Context,
attachmentID string,
pipelineVersion int,
) ([]domain.AttachmentVariant, error) {
if pipelineVersion < 1 {
pipelineVersion = 1
}
rows, err := s.pool.Query(ctx, `
SELECT name, object_key, content_type, size_bytes, width, height, sha256, pipeline_version
FROM attachment_variants
WHERE attachment_id = $1 AND pipeline_version = $2
ORDER BY name
`, attachmentID, pipelineVersion)
if err != nil {
return nil, fmt.Errorf("query attachment variants: %w", err)
}
defer rows.Close()
variants := make([]domain.AttachmentVariant, 0)
for rows.Next() {
var variant domain.AttachmentVariant
var digest []byte
if err = rows.Scan(&variant.Name, &variant.ObjectKey, &variant.ContentType, &variant.SizeBytes, &variant.Width, &variant.Height, &digest, &variant.PipelineVersion); err != nil {
return nil, fmt.Errorf("scan attachment variant: %w", err)
}
variant.SHA256 = fmt.Sprintf("%x", digest)
variants = append(variants, variant)
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("iterate attachment variants: %w", err)
}
return variants, nil
}
var _ reconcile.MetadataStore = (*PostgreSQLStore)(nil)
+278
View File
@@ -0,0 +1,278 @@
package postgres
import (
"context"
"errors"
"fmt"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
) (domain.Chat, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
transaction, err := s.pool.Begin(queryContext)
if err != nil {
return domain.Chat{}, fmt.Errorf(
"begin create chat transaction: %w",
err,
)
}
defer func() {
_ = transaction.Rollback(queryContext)
}()
chat := domain.Chat{
ID: uuid.NewString(),
Title: title,
MemberIDs: append([]string(nil), memberIDs...),
}
err = transaction.QueryRow(
queryContext,
`
INSERT INTO chats (
id,
title
)
VALUES ($1, $2)
RETURNING created_at
`,
chat.ID,
chat.Title,
).Scan(&chat.CreatedAt)
if err != nil {
return domain.Chat{}, fmt.Errorf("insert chat: %w", err)
}
for position, memberID := range memberIDs {
commandTag, insertErr := transaction.Exec(
queryContext,
`
INSERT INTO chat_members (
chat_id,
user_id,
position
)
SELECT
$1,
id,
$3
FROM users
WHERE id = $2
`,
chat.ID,
memberID,
position,
)
if insertErr != nil {
return domain.Chat{}, fmt.Errorf(
"insert chat member %s: %w",
memberID,
insertErr,
)
}
// INSERT ... SELECT не вставляет строку, если пользователя нет.
// Возврат из функции активирует deferred Rollback: уже созданные
// chat и предыдущие membership-строки не останутся в базе.
if commandTag.RowsAffected() != 1 {
return domain.Chat{}, fmt.Errorf(
"%w: member %s",
ErrNotFound,
memberID,
)
}
}
if err = transaction.Commit(queryContext); err != nil {
return domain.Chat{}, fmt.Errorf(
"commit create chat transaction: %w",
err,
)
}
return chat, nil
}
func (s *PostgreSQLStore) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var chat domain.Chat
err := s.pool.QueryRow(
queryContext,
`
SELECT
chat.id::text,
chat.title,
chat.created_at,
array_agg(
member.user_id::text
ORDER BY member.position
)
FROM chats AS chat
JOIN chat_members AS caller
ON caller.chat_id = chat.id
AND caller.user_id = $2
JOIN chat_members AS member
ON member.chat_id = chat.id
WHERE chat.id = $1
GROUP BY
chat.id,
chat.title,
chat.created_at
`,
chatID,
callerID,
).Scan(
&chat.ID,
&chat.Title,
&chat.CreatedAt,
&chat.MemberIDs,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.Chat{}, ErrNotFound
}
if err != nil {
return domain.Chat{}, fmt.Errorf("select chat by id: %w", err)
}
return chat, nil
}
func (s *PostgreSQLStore) GetChatsForUser(
ctx context.Context,
userID string,
limit int,
cursor *domain.ChatCursor,
) ([]domain.Chat, bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var (
rows pgx.Rows
err error
)
if cursor == nil {
rows, err = s.pool.Query(
queryContext,
`
SELECT
chat.id::text,
chat.title,
chat.created_at,
array_agg(
member.user_id::text
ORDER BY member.position
)
FROM chat_members AS own_membership
JOIN chats AS chat
ON chat.id = own_membership.chat_id
JOIN chat_members AS member
ON member.chat_id = chat.id
WHERE own_membership.user_id = $1
GROUP BY
chat.id,
chat.title,
chat.created_at
ORDER BY
chat.created_at,
chat.id
LIMIT $2
`,
userID,
limit+1,
)
} else {
rows, err = s.pool.Query(
queryContext,
`
SELECT
chat.id::text,
chat.title,
chat.created_at,
array_agg(
member.user_id::text
ORDER BY member.position
)
FROM chat_members AS own_membership
JOIN chats AS chat
ON chat.id = own_membership.chat_id
JOIN chat_members AS member
ON member.chat_id = chat.id
WHERE own_membership.user_id = $1
AND (chat.created_at, chat.id) > ($2, $3)
GROUP BY
chat.id,
chat.title,
chat.created_at
ORDER BY
chat.created_at,
chat.id
LIMIT $4
`,
userID,
cursor.CreatedAt,
cursor.ChatID,
limit+1,
)
}
if err != nil {
return nil, false, fmt.Errorf(
"query chats for user: %w",
err,
)
}
defer rows.Close()
items := make([]domain.Chat, 0, limit+1)
for rows.Next() {
var chat domain.Chat
if err := rows.Scan(
&chat.ID,
&chat.Title,
&chat.CreatedAt,
&chat.MemberIDs,
); err != nil {
return nil, false, fmt.Errorf(
"scan chat page: %w",
err,
)
}
items = append(items, chat)
}
if err := rows.Err(); err != nil {
return nil, false, fmt.Errorf(
"iterate chat page: %w",
err,
)
}
hasMore := len(items) > limit
if hasMore {
items = items[:limit]
}
return items, hasMore, nil
}
+5
View File
@@ -0,0 +1,5 @@
package postgres
import "mtusi2026lab7/internal/application"
var _ application.Repository = (*PostgreSQLStore)(nil)
+8
View File
@@ -0,0 +1,8 @@
package postgres
import "mtusi2026lab7/internal/domain"
var (
ErrNotFound = domain.ErrNotFound
ErrConflict = domain.ErrConflict
)
@@ -0,0 +1,75 @@
package postgres
import (
"context"
"fmt"
"time"
)
func (s *PostgreSQLStore) AllowLoginAttempt(
ctx context.Context,
identifierHash [32]byte,
now time.Time,
window time.Duration,
limit int,
) (bool, time.Duration, error) {
if err := s.maybePruneExpiredState(ctx, now); err != nil {
return false, 0, err
}
if err := s.maybePruneExpiredLoginRateState(ctx, now, window); err != nil {
return false, 0, err
}
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var attempts int
var windowStartedAt time.Time
err := s.pool.QueryRow(queryContext, `
INSERT INTO login_rate_limits (
identifier_hash, window_started_at, attempts
)
VALUES ($1, $2, 1)
ON CONFLICT (identifier_hash) DO UPDATE
SET
window_started_at = CASE
WHEN login_rate_limits.window_started_at <= $3
THEN EXCLUDED.window_started_at
ELSE login_rate_limits.window_started_at
END,
attempts = CASE
WHEN login_rate_limits.window_started_at <= $3 THEN 1
ELSE login_rate_limits.attempts + 1
END
RETURNING attempts, window_started_at
`, identifierHash[:], now.UTC(), now.UTC().Add(-window)).Scan(
&attempts,
&windowStartedAt,
)
if err != nil {
return false, 0, fmt.Errorf("update login rate limit: %w", err)
}
if attempts <= limit {
return true, 0, nil
}
retryAfter := windowStartedAt.Add(window).Sub(now.UTC())
if retryAfter < time.Second {
retryAfter = time.Second
}
return false, retryAfter, nil
}
func (s *PostgreSQLStore) ResetLoginAttempts(
ctx context.Context,
identifierHash [32]byte,
) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
if _, err := s.pool.Exec(
queryContext,
`DELETE FROM login_rate_limits WHERE identifier_hash = $1`,
identifierHash[:],
); err != nil {
return fmt.Errorf("reset login rate limit: %w", err)
}
return nil
}
+99
View File
@@ -0,0 +1,99 @@
package postgres
import (
"context"
"fmt"
"time"
)
const (
expiredStatePruneEvery = 128
expiredStatePruneBatch = 256
)
// maybePruneExpiredState bounds session/idempotency table growth without adding
// a cleanup round trip to every request. The first operation after process
// start prunes immediately; later operations amortize one bounded indexed
// delete per expiredStatePruneEvery writes.
func (s *PostgreSQLStore) maybePruneExpiredState(ctx context.Context, now time.Time) error {
iteration := s.expiredStatePruneCounter.Add(1)
if iteration != 1 && iteration%expiredStatePruneEvery != 0 {
return nil
}
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(queryContext, `
WITH stale_sessions AS (
SELECT token_hash
FROM sessions
WHERE expires_at <= $1
ORDER BY expires_at
LIMIT $2
FOR UPDATE SKIP LOCKED
), deleted_sessions AS (
DELETE FROM sessions AS target
USING stale_sessions AS stale
WHERE target.token_hash = stale.token_hash
RETURNING 1
), stale_idempotency AS (
SELECT user_id, method, canonical_path, idempotency_key
FROM message_idempotency
WHERE expires_at <= $1
ORDER BY expires_at
LIMIT $2
FOR UPDATE SKIP LOCKED
), deleted_idempotency AS (
DELETE FROM message_idempotency AS target
USING stale_idempotency AS stale
WHERE target.user_id = stale.user_id
AND target.method = stale.method
AND target.canonical_path = stale.canonical_path
AND target.idempotency_key = stale.idempotency_key
RETURNING 1
)
SELECT
(SELECT count(*) FROM deleted_sessions),
(SELECT count(*) FROM deleted_idempotency)
`, now.UTC(), expiredStatePruneBatch)
if err != nil {
return fmt.Errorf("prune expired auth state: %w", err)
}
return nil
}
// maybePruneExpiredLoginRateState uses the configured limiter window as the
// cutoff. Comparing with now directly would delete active windows and weaken
// the limiter whenever maintenance runs.
func (s *PostgreSQLStore) maybePruneExpiredLoginRateState(
ctx context.Context,
now time.Time,
window time.Duration,
) error {
iteration := s.loginRatePruneCounter.Add(1)
if iteration != 1 && iteration%expiredStatePruneEvery != 0 {
return nil
}
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(queryContext, `
WITH stale_login_limits AS (
SELECT identifier_hash
FROM login_rate_limits
WHERE window_started_at <= $1
ORDER BY window_started_at
LIMIT $2
FOR UPDATE SKIP LOCKED
)
DELETE FROM login_rate_limits AS target
USING stale_login_limits AS stale
WHERE target.identifier_hash = stale.identifier_hash
`, now.UTC().Add(-window), expiredStatePruneBatch)
if err != nil {
return fmt.Errorf("prune expired login rate state: %w", err)
}
return nil
}
+426
View File
@@ -0,0 +1,426 @@
package postgres
import (
"bytes"
"context"
"errors"
"fmt"
"time"
"mtusi2026lab7/internal/application"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateMessageIdempotently(
ctx context.Context,
write application.IdempotentMessageWrite,
) (domain.Message, error) {
if err := s.maybePruneExpiredState(ctx, time.Now()); err != nil {
return domain.Message{}, err
}
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
if err != nil {
return domain.Message{}, fmt.Errorf("begin idempotent message transaction: %w", err)
}
defer func() { _ = transaction.Rollback(queryContext) }()
var isMember bool
err = transaction.QueryRow(
queryContext,
`
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1
AND user_id = $2
)
`,
write.ChatID,
write.ActorID,
).Scan(&isMember)
if err != nil {
return domain.Message{}, fmt.Errorf("check chat membership: %w", err)
}
if !isMember {
return domain.Message{}, ErrNotFound
}
attachmentUUIDs := make([]uuid.UUID, len(write.AttachmentIDs))
for index, attachmentID := range write.AttachmentIDs {
parsedID, parseErr := uuid.Parse(attachmentID)
if parseErr != nil {
return domain.Message{}, fmt.Errorf("parse validated attachment id: %w", parseErr)
}
attachmentUUIDs[index] = parsedID
}
if len(attachmentUUIDs) > 0 {
rows, queryError := transaction.Query(
queryContext,
`
SELECT id::text, status
FROM attachments
WHERE chat_id = $1
AND id = ANY($2::uuid[])
ORDER BY id
FOR UPDATE
`,
write.ChatID,
attachmentUUIDs,
)
if queryError != nil {
return domain.Message{}, fmt.Errorf("lock message attachments: %w", queryError)
}
availableCount := 0
eligibleCount := 0
for rows.Next() {
var attachmentID string
var status domain.AttachmentStatus
if queryError = rows.Scan(&attachmentID, &status); queryError != nil {
rows.Close()
return domain.Message{}, fmt.Errorf("scan locked message attachment: %w", queryError)
}
availableCount++
if status != domain.AttachmentStatusFailed {
eligibleCount++
}
}
queryError = rows.Err()
rows.Close()
if queryError != nil {
return domain.Message{}, fmt.Errorf("iterate locked message attachments: %w", queryError)
}
if availableCount != len(attachmentUUIDs) {
return domain.Message{}, ErrNotFound
}
if eligibleCount != len(attachmentUUIDs) {
return domain.Message{}, application.ErrAttachmentNotReady
}
}
_, err = transaction.Exec(
queryContext,
`
DELETE FROM message_idempotency
WHERE user_id = $1
AND method = $2
AND canonical_path = $3
AND idempotency_key = $4
AND expires_at <= CURRENT_TIMESTAMP
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
)
if err != nil {
return domain.Message{}, fmt.Errorf("delete expired idempotency key: %w", err)
}
message := domain.Message{
ID: uuid.NewString(),
ChatID: write.ChatID,
SenderID: write.ActorID,
Text: write.Text,
AttachmentIDs: append([]string(nil), write.AttachmentIDs...),
}
var storedHash []byte
var storedMessageID string
err = transaction.QueryRow(
queryContext,
`
INSERT INTO message_idempotency (
user_id,
method,
canonical_path,
idempotency_key,
request_hash,
message_id,
expires_at
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
CURRENT_TIMESTAMP + $7 * INTERVAL '1 second'
)
ON CONFLICT DO NOTHING
RETURNING request_hash, message_id::text
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
write.RequestHash[:],
message.ID,
int64(write.TTL/time.Second),
).Scan(&storedHash, &storedMessageID)
if errors.Is(err, pgx.ErrNoRows) {
err = transaction.QueryRow(
queryContext,
`
SELECT request_hash, message_id::text
FROM message_idempotency
WHERE user_id = $1
AND method = $2
AND canonical_path = $3
AND idempotency_key = $4
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
).Scan(&storedHash, &storedMessageID)
if err != nil {
return domain.Message{}, fmt.Errorf("read idempotency result: %w", err)
}
if !bytes.Equal(storedHash, write.RequestHash[:]) {
return domain.Message{}, application.ErrIdempotencyConflict
}
err = transaction.QueryRow(
queryContext,
`
SELECT
id::text,
chat_id::text,
sender_id::text,
text,
created_at,
COALESCE(
ARRAY(
SELECT attachment_id::text
FROM message_attachments
WHERE message_id = messages.id
ORDER BY position
), ARRAY[]::text[]
)
FROM messages
WHERE id = $1
`,
storedMessageID,
).Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
&message.AttachmentIDs,
)
if err != nil {
return domain.Message{}, fmt.Errorf("read idempotent message: %w", err)
}
if err = transaction.Commit(queryContext); err != nil {
return domain.Message{}, fmt.Errorf("commit idempotency replay: %w", err)
}
return message, nil
}
if err != nil {
return domain.Message{}, fmt.Errorf("claim idempotency key: %w", err)
}
err = transaction.QueryRow(
queryContext,
`
INSERT INTO messages (
id,
chat_id,
sender_id,
text
)
VALUES ($1, $2, $3, $4)
RETURNING created_at
`,
message.ID,
message.ChatID,
message.SenderID,
message.Text,
).Scan(&message.CreatedAt)
if err != nil {
return domain.Message{}, fmt.Errorf("insert message: %w", err)
}
if len(attachmentUUIDs) > 0 {
_, err = transaction.Exec(
queryContext,
`
INSERT INTO message_attachments (
message_id,
chat_id,
attachment_id,
position
)
SELECT $1, $2, attachment_id, (ordinality - 1)::smallint
FROM unnest($3::uuid[]) WITH ORDINALITY AS input(attachment_id, ordinality)
`,
message.ID,
message.ChatID,
attachmentUUIDs,
)
if err != nil {
return domain.Message{}, fmt.Errorf("link message attachments: %w", err)
}
}
if err = transaction.Commit(queryContext); err != nil {
return domain.Message{}, fmt.Errorf("commit idempotent message: %w", err)
}
return message, nil
}
func (s *PostgreSQLStore) GetMessages(
ctx context.Context,
chatID string,
callerID string,
limit int,
cursor *domain.MessageCursor,
) ([]domain.Message, bool, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var isMember bool
err := s.pool.QueryRow(
queryContext,
`
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1
AND user_id = $2
)
`,
chatID,
callerID,
).Scan(&isMember)
if err != nil {
return nil, false, fmt.Errorf(
"check chat membership: %w",
err,
)
}
if !isMember {
return nil, false, ErrNotFound
}
var rows pgx.Rows
if cursor == nil {
rows, err = s.pool.Query(
queryContext,
`
SELECT
id::text,
chat_id::text,
sender_id::text,
text,
created_at,
COALESCE(
ARRAY(
SELECT attachment_id::text
FROM message_attachments
WHERE message_id = messages.id
ORDER BY position
), ARRAY[]::text[]
)
FROM messages
WHERE chat_id = $1
ORDER BY
created_at,
id
LIMIT $2
`,
chatID,
limit+1,
)
} else {
rows, err = s.pool.Query(
queryContext,
`
SELECT
id::text,
chat_id::text,
sender_id::text,
text,
created_at,
COALESCE(
ARRAY(
SELECT attachment_id::text
FROM message_attachments
WHERE message_id = messages.id
ORDER BY position
), ARRAY[]::text[]
)
FROM messages
WHERE chat_id = $1
AND (created_at, id) > ($2, $3)
ORDER BY
created_at,
id
LIMIT $4
`,
chatID,
cursor.CreatedAt,
cursor.MessageID,
limit+1,
)
}
if err != nil {
return nil, false, fmt.Errorf(
"query messages: %w",
err,
)
}
defer rows.Close()
items := make([]domain.Message, 0, limit+1)
for rows.Next() {
var message domain.Message
if err := rows.Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
&message.AttachmentIDs,
); err != nil {
return nil, false, fmt.Errorf(
"scan message page: %w",
err,
)
}
items = append(items, message)
}
if err := rows.Err(); err != nil {
return nil, false, fmt.Errorf(
"iterate message page: %w",
err,
)
}
hasMore := len(items) > limit
if hasMore {
items = items[:limit]
}
return items, hasMore, nil
}
+31
View File
@@ -0,0 +1,31 @@
package postgres
import (
"context"
"fmt"
"time"
)
func (s *PostgreSQLStore) AttachmentQueueStats(
ctx context.Context,
now time.Time,
) (int64, float64, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var depth int64
var oldestAge float64
err := s.pool.QueryRow(queryContext, `
SELECT
COUNT(*),
COALESCE(EXTRACT(EPOCH FROM ($1::timestamptz - MIN(created_at))), 0)
FROM attachment_jobs
WHERE status = 'queued'
`, now).Scan(&depth, &oldestAge)
if err != nil {
return 0, 0, fmt.Errorf("read attachment queue stats: %w", err)
}
if oldestAge < 0 {
oldestAge = 0
}
return depth, oldestAge, nil
}
+111
View File
@@ -0,0 +1,111 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"mtusi2026lab7/internal/domain"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateSession(
ctx context.Context,
tokenHash []byte,
userID string,
expiresAt time.Time,
) error {
if err := s.maybePruneExpiredState(ctx, time.Now()); err != nil {
return err
}
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(
queryContext,
`
INSERT INTO sessions (
token_hash,
user_id,
expires_at
)
VALUES ($1, $2, $3)
`,
tokenHash,
userID,
expiresAt,
)
if err != nil {
return fmt.Errorf("insert session: %w", err)
}
return nil
}
func (s *PostgreSQLStore) GetUserBySession(
ctx context.Context,
tokenHash []byte,
) (domain.User, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var user domain.User
err := s.pool.QueryRow(
queryContext,
`
SELECT
app_user.id::text,
app_user.username,
app_user.display_name,
app_user.created_at
FROM sessions AS session
JOIN users AS app_user
ON app_user.id = session.user_id
WHERE session.token_hash = $1
AND session.expires_at > CURRENT_TIMESTAMP
`,
tokenHash,
).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.User{}, ErrNotFound
}
if err != nil {
return domain.User{}, fmt.Errorf(
"select user by session: %w",
err,
)
}
return user, nil
}
func (s *PostgreSQLStore) DeleteSession(
ctx context.Context,
tokenHash []byte,
) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(
queryContext,
`
DELETE FROM sessions
WHERE token_hash = $1
`,
tokenHash,
)
if err != nil {
return fmt.Errorf("delete session: %w", err)
}
return nil
}
+43
View File
@@ -0,0 +1,43 @@
package postgres
import (
"context"
"sync/atomic"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
type PostgreSQLStore struct {
pool *pgxpool.Pool
queryTimeout time.Duration
expiredStatePruneCounter atomic.Uint64
loginRatePruneCounter atomic.Uint64
}
func NewPostgreSQLStore(
pool *pgxpool.Pool,
queryTimeout time.Duration,
) *PostgreSQLStore {
return &PostgreSQLStore{
pool: pool,
queryTimeout: queryTimeout,
}
}
func (s *PostgreSQLStore) Ping(ctx context.Context) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
return s.pool.Ping(queryContext)
}
func (s *PostgreSQLStore) Close() {
s.pool.Close()
}
func (s *PostgreSQLStore) withTimeout(
ctx context.Context,
) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, s.queryTimeout)
}
+165
View File
@@ -0,0 +1,165 @@
package postgres
import (
"context"
"errors"
"fmt"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
func (s *PostgreSQLStore) CreateUser(
ctx context.Context,
username string,
displayName string,
passwordHash string,
) (domain.User, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
user := domain.User{
ID: uuid.NewString(),
Username: username,
DisplayName: displayName,
}
err := s.pool.QueryRow(
queryContext,
`
INSERT INTO users (
id,
username,
display_name,
password_hash
)
VALUES ($1, $2, $3, $4)
RETURNING created_at
`,
user.ID,
user.Username,
user.DisplayName,
passwordHash,
).Scan(&user.CreatedAt)
if err == nil {
return user, nil
}
var postgresError *pgconn.PgError
if errors.As(err, &postgresError) &&
postgresError.Code == "23505" &&
postgresError.ConstraintName == "users_username_unique" {
return domain.User{}, ErrConflict
}
return domain.User{}, fmt.Errorf("insert user: %w", err)
}
func (s *PostgreSQLStore) GetUserByID(
ctx context.Context,
userID string,
) (domain.User, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var user domain.User
err := s.pool.QueryRow(
queryContext,
`
SELECT
id::text,
username,
display_name,
created_at
FROM users
WHERE id = $1
`,
userID,
).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.User{}, ErrNotFound
}
if err != nil {
return domain.User{}, fmt.Errorf("select user by id: %w", err)
}
return user, nil
}
func (s *PostgreSQLStore) GetUserByUsername(
ctx context.Context,
username string,
) (domain.User, string, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
var (
user domain.User
passwordHash string
)
err := s.pool.QueryRow(
queryContext,
`
SELECT
id::text,
username,
display_name,
created_at,
password_hash
FROM users
WHERE username = $1
`,
username,
).Scan(
&user.ID,
&user.Username,
&user.DisplayName,
&user.CreatedAt,
&passwordHash,
)
if errors.Is(err, pgx.ErrNoRows) {
return domain.User{}, "", ErrNotFound
}
if err != nil {
return domain.User{}, "", fmt.Errorf(
"select user by username: %w",
err,
)
}
return user, passwordHash, nil
}
func (s *PostgreSQLStore) UpdatePasswordHash(
ctx context.Context,
userID string,
previousHash string,
newHash string,
) error {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
_, err := s.pool.Exec(
queryContext,
`UPDATE users SET password_hash = $1 WHERE id = $2 AND password_hash = $3`,
newHash,
userID,
previousHash,
)
if err != nil {
return fmt.Errorf("update password hash: %w", err)
}
return nil
}
+175
View File
@@ -0,0 +1,175 @@
package redis
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
goredis "github.com/redis/go-redis/v9"
)
const chatKeyPrefix = "chat:v2:"
var ErrMiss = errors.New("cache miss")
// ChatCache хранит только производную копию неизменяемых данных чата.
// PostgreSQL остаётся источником истины.
type ChatCache interface {
Get(ctx context.Context, chatID string) (domain.Chat, error)
Set(ctx context.Context, chat domain.Chat) error
}
type RedisChatCache struct {
client *goredis.Client
ttl time.Duration
operationTimeout time.Duration
}
func NewRedisChatCache(
redisURL string,
ttl time.Duration,
operationTimeout time.Duration,
poolSize int,
) (*RedisChatCache, error) {
options, err := goredis.ParseURL(strings.TrimSpace(redisURL))
if err != nil {
return nil, fmt.Errorf("parse Redis URL: %w", err)
}
options.DialTimeout = operationTimeout
options.ReadTimeout = operationTimeout
options.WriteTimeout = operationTimeout
options.PoolTimeout = operationTimeout
options.PoolSize = poolSize
options.MaxRetries = -1
return &RedisChatCache{
client: goredis.NewClient(options),
ttl: ttl,
operationTimeout: operationTimeout,
}, nil
}
func (c *RedisChatCache) Ping(ctx context.Context) error {
operationContext, cancel := c.withTimeout(ctx)
defer cancel()
if err := c.client.Ping(operationContext).Err(); err != nil {
return fmt.Errorf("ping Redis: %w", err)
}
return nil
}
func (c *RedisChatCache) Close() error {
return c.client.Close()
}
func (c *RedisChatCache) Get(
ctx context.Context,
chatID string,
) (domain.Chat, error) {
operationContext, cancel := c.withTimeout(ctx)
defer cancel()
payload, err := c.client.Get(
operationContext,
chatKey(chatID),
).Bytes()
if errors.Is(err, goredis.Nil) {
return domain.Chat{}, ErrMiss
}
if err != nil {
return domain.Chat{}, fmt.Errorf("get cached chat: %w", err)
}
var chat domain.Chat
if err = json.Unmarshal(payload, &chat); err != nil {
c.deleteInvalidValue(operationContext, chatID)
return domain.Chat{}, fmt.Errorf("decode cached chat: %w", err)
}
if err = validateCachedChat(chat, chatID); err != nil {
c.deleteInvalidValue(operationContext, chatID)
return domain.Chat{}, err
}
return chat, nil
}
func (c *RedisChatCache) Set(
ctx context.Context,
chat domain.Chat,
) error {
payload, err := json.Marshal(chat)
if err != nil {
return fmt.Errorf("encode chat for cache: %w", err)
}
operationContext, cancel := c.withTimeout(ctx)
defer cancel()
if err = c.client.Set(
operationContext,
chatKey(chat.ID),
payload,
c.ttl,
).Err(); err != nil {
return fmt.Errorf("cache chat: %w", err)
}
return nil
}
func (c *RedisChatCache) withTimeout(
ctx context.Context,
) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, c.operationTimeout)
}
func (c *RedisChatCache) deleteInvalidValue(
ctx context.Context,
chatID string,
) {
_ = c.client.Del(ctx, chatKey(chatID)).Err()
}
func chatKey(chatID string) string {
return chatKeyPrefix + chatID
}
func validateCachedChat(chat domain.Chat, expectedID string) error {
if chat.ID != expectedID {
return errors.New("cached chat id does not match cache key")
}
if _, err := uuid.Parse(chat.ID); err != nil {
return errors.New("cached chat contains invalid id")
}
if strings.TrimSpace(chat.Title) == "" || chat.CreatedAt.IsZero() {
return errors.New("cached chat is incomplete")
}
if len(chat.MemberIDs) == 0 {
return errors.New("cached chat has no members")
}
seenMembers := make(map[string]struct{}, len(chat.MemberIDs))
for _, memberID := range chat.MemberIDs {
if _, err := uuid.Parse(memberID); err != nil {
return errors.New("cached chat contains invalid member id")
}
if _, exists := seenMembers[memberID]; exists {
return errors.New("cached chat contains duplicate member id")
}
seenMembers[memberID] = struct{}{}
}
return nil
}
var _ ChatCache = (*RedisChatCache)(nil)
@@ -0,0 +1,67 @@
package application
import (
"context"
"fmt"
"io"
"mtusi2026lab7/internal/domain"
)
type AttachmentDownload struct {
Body io.ReadCloser
ContentType string
Filename string
SizeBytes int64
}
func (s *Service) GetAttachment(ctx context.Context, attachmentID, actorID string) (domain.Attachment, error) {
return s.repository.GetAttachment(ctx, attachmentID, actorID)
}
func (s *Service) DownloadAttachment(ctx context.Context, attachmentID, actorID, variantName string) (AttachmentDownload, error) {
attachment, err := s.repository.GetAttachment(ctx, attachmentID, actorID)
if err != nil {
return AttachmentDownload{}, err
}
if attachment.Status != domain.AttachmentStatusReady {
return AttachmentDownload{}, ErrAttachmentNotReady
}
if s.objectStore == nil {
return AttachmentDownload{}, ErrStorageUnavailable
}
if variantName == "" {
variantName = "original"
}
key := attachment.ObjectKey
contentType := attachment.ContentType
sizeBytes := attachment.SizeBytes
filename := attachment.Filename
if variantName != "original" {
found := false
for _, variant := range attachment.Variants {
if variant.Name == variantName {
key = variant.ObjectKey
contentType = variant.ContentType
sizeBytes = variant.SizeBytes
filename = variant.Name + ".jpg"
found = true
break
}
}
if !found {
return AttachmentDownload{}, domain.ErrNotFound
}
}
object, err := s.objectStore.Get(ctx, key)
if err != nil {
return AttachmentDownload{}, fmt.Errorf("%w: get object", ErrStorageUnavailable)
}
if object.Body == nil || object.SizeBytes != sizeBytes {
if object.Body != nil {
_ = object.Body.Close()
}
return AttachmentDownload{}, fmt.Errorf("%w: object metadata mismatch", ErrStorageUnavailable)
}
return AttachmentDownload{Body: object.Body, ContentType: contentType, Filename: filename, SizeBytes: sizeBytes}, nil
}
+182
View File
@@ -0,0 +1,182 @@
package application
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"os"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
)
const currentAttachmentPipelineVersion = 1
func (s *Service) UploadAttachment(ctx context.Context, command UploadAttachmentCommand) (domain.Attachment, error) {
if s.objectStore == nil {
return domain.Attachment{}, ErrStorageUnavailable
}
queueRepository, ok := s.repository.(AttachmentQueueRepository)
if !ok {
return domain.Attachment{}, fmt.Errorf("attachment queue repository is not configured")
}
if command.Body == nil {
return domain.Attachment{}, fmt.Errorf("%w: attachment body is required", ErrInvalidInput)
}
if err := domain.ValidateAttachmentFilename(command.Filename); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
if err := domain.ValidateAttachmentContentType(command.DeclaredContentType); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrUnsupportedMediaType, err)
}
if _, err := s.repository.GetChatByID(ctx, command.ChatID, command.ActorID); err != nil {
return domain.Attachment{}, err
}
if err := acquireAttachmentSlot(ctx, s.attachmentUploadSlots); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: wait for upload capacity", ErrStorageUnavailable)
}
defer releaseAttachmentSlot(s.attachmentUploadSlots)
stagedFile, err := os.CreateTemp("", "mtusi-attachment-*")
if err != nil {
return domain.Attachment{}, fmt.Errorf("create bounded upload staging file: %w", err)
}
stagedPath := stagedFile.Name()
defer func() {
_ = stagedFile.Close()
_ = os.Remove(stagedPath)
}()
hasher := sha256.New()
sizeBytes, err := io.Copy(io.MultiWriter(stagedFile, hasher), io.LimitReader(command.Body, domain.MaxAttachmentSizeBytes+1))
if err != nil {
return domain.Attachment{}, fmt.Errorf("%w: read attachment body", ErrInvalidInput)
}
if sizeBytes > domain.MaxAttachmentSizeBytes {
return domain.Attachment{}, ErrPayloadTooLarge
}
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind staged attachment: %w", err)
}
imageConfig, format, err := image.DecodeConfig(stagedFile)
if err != nil {
return domain.Attachment{}, fmt.Errorf("%w: decode image header", ErrInvalidImage)
}
actualContentType, supported := contentTypeForImageFormat(format)
if !supported || actualContentType != command.DeclaredContentType {
return domain.Attachment{}, ErrUnsupportedMediaType
}
if imageConfig.Width < 1 || imageConfig.Height < 1 {
return domain.Attachment{}, ErrInvalidImage
}
if int64(imageConfig.Width) > int64(domain.MaxAttachmentPixels)/int64(imageConfig.Height) {
return domain.Attachment{}, ErrPayloadTooLarge
}
sha256Hex := hex.EncodeToString(hasher.Sum(nil))
if err = domain.ValidateReadyAttachmentMetadata(command.Filename, actualContentType, sizeBytes, sha256Hex, imageConfig.Width, imageConfig.Height); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidImage, err)
}
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind staged attachment for validation: %w", err)
}
if err = s.validateCompleteImage(ctx, stagedFile); err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return domain.Attachment{}, fmt.Errorf("%w: wait for image decoder", ErrStorageUnavailable)
}
return domain.Attachment{}, fmt.Errorf("%w: decode complete image", ErrInvalidImage)
}
now := s.now().UTC()
attachmentID := uuid.NewString()
attachment := domain.Attachment{
ID: attachmentID,
ChatID: command.ChatID,
OwnerID: command.ActorID,
Filename: command.Filename,
ObjectKey: "attachments/" + command.ChatID + "/" + attachmentID + "/original",
StagingKey: "staging/" + attachmentID + "/original",
ContentType: actualContentType,
SizeBytes: sizeBytes,
SHA256: sha256Hex,
Width: imageConfig.Width,
Height: imageConfig.Height,
PipelineVersion: currentAttachmentPipelineVersion,
Status: domain.AttachmentStatusQueued,
Variants: make([]domain.AttachmentVariant, 0),
CreatedAt: now,
UpdatedAt: now,
}
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind staged attachment for storage: %w", err)
}
if err = s.objectStore.Put(ctx, ObjectPut{Key: attachment.StagingKey, ContentType: attachment.ContentType, SizeBytes: attachment.SizeBytes, Body: stagedFile}); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: put durable staging object", ErrStorageUnavailable)
}
traceCarrier := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, traceCarrier)
job := domain.AttachmentJob{
SchemaVersion: 1,
JobID: uuid.NewString(),
Type: domain.AttachmentJobType,
AttachmentID: attachment.ID,
PipelineVersion: attachment.PipelineVersion,
Attempt: 1,
MaxAttempts: s.jobMaxAttempts,
Status: domain.AttachmentJobQueued,
AvailableAt: now,
CreatedAt: now,
UpdatedAt: now,
TraceParent: traceCarrier.Get("traceparent"),
TraceState: traceCarrier.Get("tracestate"),
}
attachment, err = queueRepository.CreateQueuedAttachment(ctx, attachment, job)
if err != nil {
// A failed COMMIT response is ambiguous. Preserve staging so a committed
// job can still finish and an uncommitted orphan can be retained/cleaned.
return domain.Attachment{}, fmt.Errorf("persist queued attachment: %w", err)
}
if attachment.Variants == nil {
attachment.Variants = make([]domain.AttachmentVariant, 0)
}
return attachment, nil
}
func acquireAttachmentSlot(ctx context.Context, slots chan struct{}) error {
select {
case slots <- struct{}{}:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func releaseAttachmentSlot(slots chan struct{}) { <-slots }
func (s *Service) validateCompleteImage(ctx context.Context, body io.Reader) error {
if err := acquireAttachmentSlot(ctx, s.attachmentDecodeSlots); err != nil {
return err
}
defer releaseAttachmentSlot(s.attachmentDecodeSlots)
_, _, err := image.Decode(body)
return err
}
func contentTypeForImageFormat(format string) (string, bool) {
switch format {
case "png":
return "image/png", true
case "jpeg":
return "image/jpeg", true
default:
return "", false
}
}
+155
View File
@@ -0,0 +1,155 @@
package application_test
import (
"bytes"
"context"
"errors"
"image"
"image/color"
"image/png"
"io"
"sync"
"testing"
"time"
"mtusi2026lab7/internal/adapter/memory"
. "mtusi2026lab7/internal/application"
"mtusi2026lab7/internal/domain"
)
type fakeObjectStore struct {
mu sync.Mutex
objects map[string][]byte
putError error
}
func newFakeObjectStore() *fakeObjectStore { return &fakeObjectStore{objects: make(map[string][]byte)} }
func (store *fakeObjectStore) Put(_ context.Context, object ObjectPut) error {
if store.putError != nil {
return store.putError
}
payload, err := io.ReadAll(object.Body)
if err != nil {
return err
}
store.mu.Lock()
store.objects[object.Key] = payload
store.mu.Unlock()
return nil
}
func (store *fakeObjectStore) Get(_ context.Context, key string) (ObjectContent, error) {
store.mu.Lock()
defer store.mu.Unlock()
payload, ok := store.objects[key]
if !ok {
return ObjectContent{}, errors.New("not found")
}
return ObjectContent{Body: io.NopCloser(bytes.NewReader(payload)), SizeBytes: int64(len(payload))}, nil
}
func (store *fakeObjectStore) Delete(_ context.Context, key string) error {
store.mu.Lock()
delete(store.objects, key)
store.mu.Unlock()
return nil
}
type interruptedReader struct{}
func (interruptedReader) Read([]byte) (int, error) { return 0, errors.New("injected read failure") }
func newAttachmentService(t *testing.T, objects ObjectStore) (*Service, string, string) {
t.Helper()
legacy := memory.NewMemoryStore()
repository := memory.NewMemoryRepository(legacy)
user, err := repository.CreateUser(context.Background(), "uploader", "Uploader", "hash")
if err != nil {
t.Fatal(err)
}
chat, err := repository.CreateChat(context.Background(), "Images", []string{user.ID})
if err != nil {
t.Fatal(err)
}
codec, err := NewCursorCodec("attachment-test-key-with-more-than-thirty-two-bytes")
if err != nil {
t.Fatal(err)
}
service, err := NewService(repository, codec, time.Hour, WithObjectStore(objects), WithJobMaxAttempts(5))
if err != nil {
t.Fatal(err)
}
return service, user.ID, chat.ID
}
func testPNG(t *testing.T) []byte {
t.Helper()
var payload bytes.Buffer
img := image.NewRGBA(image.Rect(0, 0, 320, 200))
img.Set(0, 0, color.RGBA{R: 255, A: 255})
if err := png.Encode(&payload, img); err != nil {
t.Fatal(err)
}
return payload.Bytes()
}
func TestUploadAttachmentDurablyQueuesStagingObject(t *testing.T) {
objects := newFakeObjectStore()
service, actorID, chatID := newAttachmentService(t, objects)
payload := testPNG(t)
attachment, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID, ChatID: chatID, Filename: "photo.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(payload),
})
if err != nil {
t.Fatal(err)
}
if attachment.Status != domain.AttachmentStatusQueued {
t.Fatalf("status=%s, want queued", attachment.Status)
}
if attachment.StagingKey == "" || attachment.ObjectKey == attachment.StagingKey {
t.Fatalf("staging/final keys are not separated: %+v", attachment)
}
objects.mu.Lock()
staged := append([]byte(nil), objects.objects[attachment.StagingKey]...)
objects.mu.Unlock()
if !bytes.Equal(staged, payload) {
t.Fatal("durable staging bytes differ")
}
}
func TestUploadAttachmentRejectsInvalidInputBeforeStaging(t *testing.T) {
objects := newFakeObjectStore()
service, actorID, chatID := newAttachmentService(t, objects)
cases := []struct {
name string
command UploadAttachmentCommand
target error
}{
{"unsafe filename", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "../x.png", DeclaredContentType: "image/png", Body: bytes.NewReader(testPNG(t))}, ErrInvalidInput},
{"mime", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/jpeg", Body: bytes.NewReader(testPNG(t))}, ErrUnsupportedMediaType},
{"corrupt", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: bytes.NewReader([]byte("broken"))}, ErrInvalidImage},
{"interrupted", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: interruptedReader{}}, ErrInvalidInput},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if _, err := service.UploadAttachment(context.Background(), tc.command); !errors.Is(err, tc.target) {
t.Fatalf("error=%v, want %v", err, tc.target)
}
})
}
objects.mu.Lock()
count := len(objects.objects)
objects.mu.Unlock()
if count != 0 {
t.Fatalf("invalid requests staged %d objects", count)
}
}
func TestUploadAttachmentStorageFailureDoesNotCreateQueuedMetadata(t *testing.T) {
objects := newFakeObjectStore()
objects.putError = errors.New("storage down")
service, actorID, chatID := newAttachmentService(t, objects)
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: bytes.NewReader(testPNG(t))})
if !errors.Is(err, ErrStorageUnavailable) {
t.Fatalf("error=%v, want storage unavailable", err)
}
}
+55
View File
@@ -0,0 +1,55 @@
package application
import (
"context"
"fmt"
"mtusi2026lab7/internal/domain"
)
func (s *Service) CreateChat(ctx context.Context, command CreateChatCommand) (domain.Chat, error) {
if err := domain.ValidateChatInput(command.Title, command.MemberIDs, command.ActorID); err != nil {
return domain.Chat{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
return s.repository.CreateChat(ctx, command.Title, command.MemberIDs)
}
func (s *Service) GetChat(ctx context.Context, actorID, chatID string) (domain.Chat, error) {
return s.repository.GetChatByID(ctx, chatID, actorID)
}
func (s *Service) ListChats(
ctx context.Context,
actorID string,
limit int,
cursorToken string,
) (domain.ChatPage, error) {
var cursor *domain.ChatCursor
if cursorToken != "" {
decoded, err := s.cursors.DecodeChat(cursorToken, actorID)
if err != nil {
return domain.ChatPage{}, ErrInvalidCursor
}
cursor = decoded
}
items, hasMore, err := s.repository.GetChatsForUser(ctx, actorID, limit, cursor)
if err != nil {
return domain.ChatPage{}, err
}
page := domain.ChatPage{Items: items}
if page.Items == nil {
page.Items = make([]domain.Chat, 0)
}
if hasMore {
last := page.Items[len(page.Items)-1]
next, encodeErr := s.cursors.EncodeChat(domain.ChatCursor{
CreatedAt: last.CreatedAt, ChatID: last.ID, UserID: actorID,
})
if encodeErr != nil {
return domain.ChatPage{}, encodeErr
}
page.NextCursor = &next
}
return page, nil
}
+38
View File
@@ -0,0 +1,38 @@
package application
import "io"
type CreateUserCommand struct {
Username string
DisplayName string
Password string
}
type CreateSessionCommand struct {
Username string
Password string
}
type CreateChatCommand struct {
ActorID string
Title string
MemberIDs []string
}
type SendMessageCommand struct {
ActorID string
ChatID string
Text string
AttachmentIDs []string
Method string
CanonicalPath string
IdempotencyKey string
}
type UploadAttachmentCommand struct {
ActorID string
ChatID string
Filename string
DeclaredContentType string
Body io.Reader
}
+121
View File
@@ -0,0 +1,121 @@
package application
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"time"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
)
const cursorVersion = 1
type CursorCodec struct {
key []byte
}
type cursorPayload struct {
Version int `json:"v"`
Kind string `json:"kind"`
CreatedAt string `json:"created_at"`
ID string `json:"id"`
ScopeID string `json:"scope_id"`
}
func NewCursorCodec(key string) (*CursorCodec, error) {
if len(key) < 32 {
return nil, fmt.Errorf("cursor signing key must contain at least 32 bytes")
}
return &CursorCodec{key: []byte(key)}, nil
}
func (c *CursorCodec) EncodeChat(cursor domain.ChatCursor) (string, error) {
return c.encode(cursorPayload{
Version: cursorVersion, Kind: "chat", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano),
ID: cursor.ChatID, ScopeID: cursor.UserID,
})
}
func (c *CursorCodec) DecodeChat(token, expectedUserID string) (*domain.ChatCursor, error) {
payload, err := c.decode(token, "chat", expectedUserID)
if err != nil {
return nil, err
}
return &domain.ChatCursor{CreatedAt: payload.createdAt, ChatID: payload.id, UserID: payload.scopeID}, nil
}
func (c *CursorCodec) EncodeMessage(cursor domain.MessageCursor) (string, error) {
return c.encode(cursorPayload{
Version: cursorVersion, Kind: "message", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano),
ID: cursor.MessageID, ScopeID: cursor.ChatID,
})
}
func (c *CursorCodec) DecodeMessage(token, expectedChatID string) (*domain.MessageCursor, error) {
payload, err := c.decode(token, "message", expectedChatID)
if err != nil {
return nil, err
}
return &domain.MessageCursor{CreatedAt: payload.createdAt, MessageID: payload.id, ChatID: payload.scopeID}, nil
}
func (c *CursorCodec) encode(payload cursorPayload) (string, error) {
encodedPayload, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("encode cursor payload: %w", err)
}
mac := hmac.New(sha256.New, c.key)
_, _ = mac.Write(encodedPayload)
return base64.RawURLEncoding.EncodeToString(encodedPayload) + "." +
base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
}
type decodedCursor struct {
createdAt time.Time
id string
scopeID string
}
func (c *CursorCodec) decode(token, expectedKind, expectedScopeID string) (decodedCursor, error) {
parts := strings.Split(token, ".")
if len(parts) != 2 {
return decodedCursor{}, ErrInvalidCursor
}
payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return decodedCursor{}, ErrInvalidCursor
}
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return decodedCursor{}, ErrInvalidCursor
}
mac := hmac.New(sha256.New, c.key)
_, _ = mac.Write(payloadBytes)
if !hmac.Equal(signature, mac.Sum(nil)) {
return decodedCursor{}, ErrInvalidCursor
}
var payload cursorPayload
if err = json.Unmarshal(payloadBytes, &payload); err != nil ||
payload.Version != cursorVersion || payload.Kind != expectedKind ||
payload.ScopeID != expectedScopeID {
return decodedCursor{}, ErrInvalidCursor
}
createdAt, err := time.Parse(time.RFC3339Nano, payload.CreatedAt)
if err != nil {
return decodedCursor{}, ErrInvalidCursor
}
if _, err = uuid.Parse(payload.ID); err != nil {
return decodedCursor{}, ErrInvalidCursor
}
if _, err = uuid.Parse(payload.ScopeID); err != nil {
return decodedCursor{}, ErrInvalidCursor
}
return decodedCursor{createdAt: createdAt.UTC(), id: payload.ID, scopeID: payload.ScopeID}, nil
}
+96
View File
@@ -0,0 +1,96 @@
package application
import (
"encoding/base64"
"errors"
"strings"
"testing"
"time"
"mtusi2026lab7/internal/domain"
)
const cursorTestKey = "cursor-test-key-with-more-than-thirty-two-bytes"
func TestCursorCodecRoundTrip(t *testing.T) {
codec, err := NewCursorCodec(cursorTestKey)
if err != nil {
t.Fatal(err)
}
expected := domain.MessageCursor{
CreatedAt: time.Date(2026, 10, 18, 12, 30, 0, 123, time.UTC),
MessageID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf",
ChatID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf",
}
token, err := codec.EncodeMessage(expected)
if err != nil {
t.Fatal(err)
}
actual, err := codec.DecodeMessage(token, expected.ChatID)
if err != nil {
t.Fatal(err)
}
if *actual != expected {
t.Fatalf("cursor changed after round trip: got %#v, want %#v", *actual, expected)
}
}
func TestCursorCodecRejectsTamperingAndWrongScope(t *testing.T) {
codec, err := NewCursorCodec(cursorTestKey)
if err != nil {
t.Fatal(err)
}
token, err := codec.EncodeChat(domain.ChatCursor{
CreatedAt: time.Now().UTC(),
ChatID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf",
UserID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf",
})
if err != nil {
t.Fatal(err)
}
parts := strings.Split(token, ".")
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
t.Fatal(err)
}
signature[0] ^= 1
tampered := parts[0] + "." + base64.RawURLEncoding.EncodeToString(signature)
if _, err = codec.DecodeChat(tampered, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
t.Fatalf("tampered cursor: got %v, want ErrInvalidCursor", err)
}
if _, err = codec.DecodeChat(token, "e6ca4af0-69ed-4784-8ce0-ee035299fe08"); !errors.Is(err, ErrInvalidCursor) {
t.Fatalf("wrong scope: got %v, want ErrInvalidCursor", err)
}
if _, err = codec.DecodeMessage(token, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
t.Fatalf("wrong cursor kind: got %v, want ErrInvalidCursor", err)
}
}
func TestCursorCodecRequiresStrongSharedKey(t *testing.T) {
if _, err := NewCursorCodec("too-short"); err == nil {
t.Fatal("expected short cursor signing key to be rejected")
}
}
func TestCursorCodecRejectsSignedInvalidFieldTypesBeforeSQL(t *testing.T) {
codec, err := NewCursorCodec(cursorTestKey)
if err != nil {
t.Fatal(err)
}
chatID := "9fa3f49c-e62e-4209-8414-d6d5f69805bf"
validMessageID := "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf"
testCases := []cursorPayload{
{Version: cursorVersion, Kind: "message", CreatedAt: "not-a-time", ID: validMessageID, ScopeID: chatID},
{Version: cursorVersion, Kind: "message", CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), ID: "not-a-uuid", ScopeID: chatID},
}
for _, payload := range testCases {
token, encodeErr := codec.encode(payload)
if encodeErr != nil {
t.Fatal(encodeErr)
}
if _, decodeErr := codec.DecodeMessage(token, chatID); !errors.Is(decodeErr, ErrInvalidCursor) {
t.Fatalf("invalid signed cursor returned %v, want ErrInvalidCursor", decodeErr)
}
}
}
+16
View File
@@ -0,0 +1,16 @@
package application
import "errors"
var (
ErrInvalidCursor = errors.New("invalid cursor")
ErrInvalidCredentials = errors.New("invalid credentials")
ErrInvalidInput = errors.New("invalid input")
ErrCredentialState = errors.New("invalid stored credential state")
ErrIdempotencyConflict = errors.New("idempotency key is already used for another request")
ErrAttachmentNotReady = errors.New("attachment is not ready")
ErrPayloadTooLarge = errors.New("payload too large")
ErrUnsupportedMediaType = errors.New("unsupported media type")
ErrInvalidImage = errors.New("invalid image")
ErrStorageUnavailable = errors.New("object storage unavailable")
)
+88
View File
@@ -0,0 +1,88 @@
package application
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
)
type canonicalMessageRequest struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) {
attachmentIDs := append([]string(nil), command.AttachmentIDs...)
if attachmentIDs == nil {
attachmentIDs = make([]string, 0)
}
if err := domain.ValidateMessageInput(command.Text, attachmentIDs); err != nil {
return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
for index, attachmentID := range attachmentIDs {
attachmentIDs[index] = uuid.MustParse(attachmentID).String()
}
canonicalBody, err := json.Marshal(canonicalMessageRequest{
Text: command.Text,
AttachmentIDs: attachmentIDs,
})
if err != nil {
return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err)
}
return s.repository.CreateMessageIdempotently(ctx, IdempotentMessageWrite{
ActorID: command.ActorID,
ChatID: command.ChatID,
Text: command.Text,
AttachmentIDs: attachmentIDs,
Method: command.Method,
CanonicalPath: command.CanonicalPath,
Key: command.IdempotencyKey,
RequestHash: sha256.Sum256(canonicalBody),
TTL: s.idempotencyTTL,
})
}
func (s *Service) ListMessages(
ctx context.Context,
actorID string,
chatID string,
limit int,
cursorToken string,
) (domain.MessagePage, error) {
var cursor *domain.MessageCursor
if cursorToken != "" {
decoded, err := s.cursors.DecodeMessage(cursorToken, chatID)
if err != nil {
return domain.MessagePage{}, ErrInvalidCursor
}
cursor = decoded
}
items, hasMore, err := s.repository.GetMessages(ctx, chatID, actorID, limit, cursor)
if err != nil {
return domain.MessagePage{}, err
}
page := domain.MessagePage{Items: items}
if page.Items == nil {
page.Items = make([]domain.Message, 0)
}
if hasMore {
last := page.Items[len(page.Items)-1]
next, encodeErr := s.cursors.EncodeMessage(domain.MessageCursor{
CreatedAt: last.CreatedAt, MessageID: last.ID, ChatID: chatID,
})
if encodeErr != nil {
return domain.MessagePage{}, encodeErr
}
page.NextCursor = &next
}
return page, nil
}
+81
View File
@@ -0,0 +1,81 @@
package application
import (
"context"
"io"
"time"
"mtusi2026lab7/internal/domain"
)
type UserRepository interface {
CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error)
GetUserByUsername(ctx context.Context, username string) (domain.User, string, error)
UpdatePasswordHash(ctx context.Context, userID, previousHash, newHash string) error
}
type SessionRepository interface {
CreateSession(ctx context.Context, tokenHash []byte, userID string, expiresAt time.Time) error
GetUserBySession(ctx context.Context, tokenHash []byte) (domain.User, error)
DeleteSession(ctx context.Context, tokenHash []byte) error
}
type ChatRepository interface {
CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error)
GetChatByID(ctx context.Context, chatID, callerID string) (domain.Chat, error)
GetChatsForUser(ctx context.Context, userID string, limit int, cursor *domain.ChatCursor) ([]domain.Chat, bool, error)
}
type IdempotentMessageWrite struct {
ActorID string
ChatID string
Text string
AttachmentIDs []string
Method string
CanonicalPath string
Key string
RequestHash [32]byte
TTL time.Duration
}
type MessageRepository interface {
CreateMessageIdempotently(ctx context.Context, write IdempotentMessageWrite) (domain.Message, error)
GetMessages(ctx context.Context, chatID, callerID string, limit int, cursor *domain.MessageCursor) ([]domain.Message, bool, error)
}
type AttachmentRepository interface {
CreateAttachment(ctx context.Context, attachment domain.Attachment) (domain.Attachment, error)
MarkAttachmentReady(ctx context.Context, attachmentID string, updatedAt time.Time) (domain.Attachment, error)
MarkAttachmentFailed(ctx context.Context, attachmentID, errorCode string, updatedAt time.Time) error
GetAttachment(ctx context.Context, attachmentID, callerID string) (domain.Attachment, error)
}
type AttachmentQueueRepository interface {
CreateQueuedAttachment(ctx context.Context, attachment domain.Attachment, job domain.AttachmentJob) (domain.Attachment, error)
}
type Repository interface {
UserRepository
SessionRepository
ChatRepository
MessageRepository
AttachmentRepository
}
type ObjectPut struct {
Key string
ContentType string
SizeBytes int64
Body io.Reader
}
type ObjectContent struct {
Body io.ReadCloser
SizeBytes int64
}
type ObjectStore interface {
Put(ctx context.Context, object ObjectPut) error
Get(ctx context.Context, key string) (ObjectContent, error)
Delete(ctx context.Context, key string) error
}
+86
View File
@@ -0,0 +1,86 @@
package application
import (
"fmt"
"time"
)
const MinimumIdempotencyTTL = 24 * time.Hour
const defaultAttachmentCleanupTimeout = time.Second
const defaultAttachmentUploadConcurrency = 4
const defaultAttachmentDecodeConcurrency = 1
const defaultJobMaxAttempts = 5
type ServiceOption func(*Service) error
type Service struct {
repository Repository
cursors *CursorCodec
sessionTTL time.Duration
idempotencyTTL time.Duration
now func() time.Time
objectStore ObjectStore
attachmentCleanupTimeout time.Duration
attachmentUploadSlots chan struct{}
attachmentDecodeSlots chan struct{}
jobMaxAttempts int
}
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*Service, error) {
if repository == nil {
return nil, fmt.Errorf("repository is required")
}
if cursors == nil {
return nil, fmt.Errorf("cursor codec is required")
}
if sessionTTL <= 0 {
return nil, fmt.Errorf("session TTL must be positive")
}
service := &Service{
repository: repository,
cursors: cursors,
sessionTTL: sessionTTL,
idempotencyTTL: MinimumIdempotencyTTL,
now: func() time.Time { return time.Now().UTC() },
attachmentCleanupTimeout: defaultAttachmentCleanupTimeout,
attachmentUploadSlots: make(chan struct{}, defaultAttachmentUploadConcurrency),
attachmentDecodeSlots: make(chan struct{}, defaultAttachmentDecodeConcurrency),
jobMaxAttempts: defaultJobMaxAttempts,
}
for _, option := range options {
if err := option(service); err != nil {
return nil, err
}
}
return service, nil
}
func WithIdempotencyTTL(ttl time.Duration) ServiceOption {
return func(service *Service) error {
if ttl < MinimumIdempotencyTTL {
return fmt.Errorf("idempotency TTL must be at least %s", MinimumIdempotencyTTL)
}
service.idempotencyTTL = ttl
return nil
}
}
func WithObjectStore(objectStore ObjectStore) ServiceOption {
return func(service *Service) error {
if objectStore == nil {
return fmt.Errorf("object store is required")
}
service.objectStore = objectStore
return nil
}
}
func WithJobMaxAttempts(attempts int) ServiceOption {
return func(service *Service) error {
if attempts < 1 {
return fmt.Errorf("job max attempts must be positive")
}
service.jobMaxAttempts = attempts
return nil
}
}
+70
View File
@@ -0,0 +1,70 @@
package application
import (
"context"
"errors"
"fmt"
"mtusi2026lab7/internal/domain"
"mtusi2026lab7/internal/security"
)
const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" +
"AAAAAAAAAAAAAAAAAAAAAA$" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
func (s *Service) CreateSession(ctx context.Context, command CreateSessionCommand) (domain.Session, error) {
user, passwordHash, err := s.repository.GetUserByUsername(ctx, command.Username)
userNotFound := errors.Is(err, domain.ErrNotFound)
if userNotFound {
passwordHash = dummyPasswordHash
} else if err != nil {
return domain.Session{}, err
}
passwordMatches, verifyErr := security.VerifyPassword(command.Password, passwordHash)
if verifyErr != nil {
return domain.Session{}, fmt.Errorf("%w: %v", ErrCredentialState, verifyErr)
}
if userNotFound || !passwordMatches {
return domain.Session{}, ErrInvalidCredentials
}
needsRehash, rehashErr := security.NeedsPasswordRehash(passwordHash)
if rehashErr != nil {
return domain.Session{}, fmt.Errorf("%w: password hash policy", ErrCredentialState)
}
if needsRehash {
newHash, hashErr := security.HashPassword(command.Password)
if hashErr != nil {
return domain.Session{}, fmt.Errorf("%w: password rehash", ErrCredentialState)
}
if updateErr := s.repository.UpdatePasswordHash(ctx, user.ID, passwordHash, newHash); updateErr != nil {
return domain.Session{}, fmt.Errorf("%w: password rehash update", ErrCredentialState)
}
}
token, tokenHash, err := security.GenerateSessionToken()
if err != nil {
return domain.Session{}, fmt.Errorf("generate session token: %w", err)
}
expiresAt := s.now().Add(s.sessionTTL)
if err = s.repository.CreateSession(ctx, tokenHash, user.ID, expiresAt); err != nil {
return domain.Session{}, err
}
return domain.Session{
Token: token, TokenType: "Bearer", ExpiresAt: expiresAt, User: user,
}, nil
}
func (s *Service) Authenticate(ctx context.Context, token string) (domain.User, []byte, error) {
tokenHash := security.HashSessionToken(token)
user, err := s.repository.GetUserBySession(ctx, tokenHash)
if err != nil {
return domain.User{}, nil, err
}
return user, tokenHash, nil
}
func (s *Service) DeleteSession(ctx context.Context, tokenHash []byte) error {
return s.repository.DeleteSession(ctx, tokenHash)
}
+29
View File
@@ -0,0 +1,29 @@
package application
import (
"context"
"fmt"
"mtusi2026lab7/internal/domain"
"mtusi2026lab7/internal/security"
)
func (s *Service) CreateUser(ctx context.Context, command CreateUserCommand) (domain.User, error) {
if err := domain.ValidateUser(command.Username, command.DisplayName); err != nil {
return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
if err := security.ValidatePassword(command.Password); err != nil {
return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
passwordHash, err := security.HashPassword(command.Password)
if err != nil {
return domain.User{}, fmt.Errorf("hash password: %w", err)
}
return s.repository.CreateUser(
ctx,
command.Username,
command.DisplayName,
passwordHash,
)
}
+554
View File
@@ -0,0 +1,554 @@
package config
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"net"
"os"
"regexp"
"strconv"
"strings"
"time"
)
type Config struct {
HTTPHost string
HTTPPort string
InstanceID string
SessionTTL time.Duration
IdempotencyTTL time.Duration
SessionCookieSecure bool
CursorSigningKey string
LoginRateLimit int
LoginRateWindow time.Duration
DatabaseURL string
DatabaseMaxConns int32
DatabaseMinConns int32
DatabaseMaxConnLifetime time.Duration
DatabaseMaxConnIdleTime time.Duration
DatabaseHealthCheckPeriod time.Duration
DatabaseConnectTimeout time.Duration
DatabaseQueryTimeout time.Duration
RedisURL string
RedisCacheTTL time.Duration
RedisOperationTimeout time.Duration
RedisPoolSize int
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKeyID string
S3SecretAccessKey string
S3OperationTimeout time.Duration
BrokerURL string
WorkerConcurrency int
JobMaxAttempts int
JobTimeout time.Duration
JobRetryBase time.Duration
JobRetryMax time.Duration
JobLease time.Duration
StagingRetention time.Duration
StagingCleanupInterval time.Duration
ReadinessTimeout time.Duration
ShutdownDrainDelay time.Duration
ShutdownTimeout time.Duration
}
func Load() (Config, error) { return load(true, true) }
func LoadWorker() (Config, error) { return load(false, true) }
func LoadDispatcher() (Config, error) { return load(false, false) }
func load(requireCursor, requireS3 bool) (Config, error) {
instanceID, err := instanceIDFromEnv()
if err != nil {
return Config{}, err
}
sessionTTL, err := secondsDurationFromEnv(
"SESSION_TTL_SECONDS",
3600,
)
if err != nil {
return Config{}, err
}
idempotencyTTL, err := secondsDurationFromEnv(
"IDEMPOTENCY_TTL_SECONDS",
86400,
)
if err != nil {
return Config{}, err
}
loginRateLimit, err := int32FromEnv("LOGIN_RATE_LIMIT", 5, 1)
if err != nil {
return Config{}, err
}
loginRateWindow, err := secondsDurationFromEnv("LOGIN_RATE_WINDOW_SECONDS", 60)
if err != nil {
return Config{}, err
}
sessionCookieSecure, err := boolFromEnv("SESSION_COOKIE_SECURE", false)
if err != nil {
return Config{}, err
}
databaseURL, err := requiredValueOrFile(
"DATABASE_URL",
"DATABASE_URL_FILE",
)
if err != nil {
return Config{}, err
}
cursorSigningKey, err := roleValueOrFile(requireCursor,
"CURSOR_SIGNING_KEY",
"CURSOR_SIGNING_KEY_FILE",
)
if err != nil {
return Config{}, err
}
s3AccessKeyID, err := roleValueOrFile(requireS3,
"S3_ACCESS_KEY_ID",
"S3_ACCESS_KEY_ID_FILE",
)
if err != nil {
return Config{}, err
}
s3SecretAccessKey, err := roleValueOrFile(requireS3,
"S3_SECRET_ACCESS_KEY",
"S3_SECRET_ACCESS_KEY_FILE",
)
if err != nil {
return Config{}, err
}
s3OperationTimeout, err := durationFromEnv("S3_OPERATION_TIMEOUT", 5*time.Second)
if err != nil {
return Config{}, err
}
brokerURL, err := optionalValueOrFile("BROKER_URL", "BROKER_URL_FILE")
if err != nil {
return Config{}, err
}
workerConcurrency, err := int32FromEnv("WORKER_CONCURRENCY", 2, 1)
if err != nil {
return Config{}, err
}
jobMaxAttempts, err := int32FromEnv("JOB_MAX_ATTEMPTS", 5, 1)
if err != nil {
return Config{}, err
}
jobTimeout, err := secondsDurationFromEnv("JOB_TIMEOUT_SECONDS", 60)
if err != nil {
return Config{}, err
}
jobRetryBase, err := durationFromEnv("JOB_RETRY_BASE", 250*time.Millisecond)
if err != nil {
return Config{}, err
}
jobRetryMax, err := durationFromEnv("JOB_RETRY_MAX", 4*time.Second)
if err != nil {
return Config{}, err
}
jobLease, err := secondsDurationFromEnv("JOB_LEASE_SECONDS", 75)
if err != nil {
return Config{}, err
}
stagingRetention, err := secondsDurationFromEnv("STAGING_RETENTION_SECONDS", 86400)
if err != nil {
return Config{}, err
}
stagingCleanupInterval, err := secondsDurationFromEnv("STAGING_CLEANUP_INTERVAL_SECONDS", 30)
if err != nil {
return Config{}, err
}
databaseMaxConns, err := int32FromEnv("DB_MAX_CONNS", 10, 1)
if err != nil {
return Config{}, err
}
databaseMinConns, err := int32FromEnv("DB_MIN_CONNS", 2, 0)
if err != nil {
return Config{}, err
}
databaseMaxConnLifetime, err := durationFromEnv(
"DB_MAX_CONN_LIFETIME",
30*time.Minute,
)
if err != nil {
return Config{}, err
}
databaseMaxConnIdleTime, err := durationFromEnv(
"DB_MAX_CONN_IDLE_TIME",
5*time.Minute,
)
if err != nil {
return Config{}, err
}
databaseHealthCheckPeriod, err := durationFromEnv(
"DB_HEALTH_CHECK_PERIOD",
30*time.Second,
)
if err != nil {
return Config{}, err
}
databaseConnectTimeout, err := durationFromEnv(
"DB_CONNECT_TIMEOUT",
5*time.Second,
)
if err != nil {
return Config{}, err
}
databaseQueryTimeout, err := durationFromEnv(
"DB_QUERY_TIMEOUT",
3*time.Second,
)
if err != nil {
return Config{}, err
}
redisURL, err := optionalValueOrFile("CACHE_URL", "CACHE_URL_FILE")
if err != nil {
return Config{}, err
}
redisCacheTTL, err := durationFromEnv(
"CACHE_TTL",
5*time.Minute,
)
if err != nil {
return Config{}, err
}
redisOperationTimeout, err := durationFromEnv(
"CACHE_OPERATION_TIMEOUT",
250*time.Millisecond,
)
if err != nil {
return Config{}, err
}
redisPoolSize, err := int32FromEnv("CACHE_POOL_SIZE", 10, 1)
if err != nil {
return Config{}, err
}
readinessTimeout, err := durationFromEnv(
"READINESS_TIMEOUT",
2*time.Second,
)
if err != nil {
return Config{}, err
}
shutdownDrainDelay, err := durationFromEnv(
"SHUTDOWN_DRAIN_DELAY",
2*time.Second,
)
if err != nil {
return Config{}, err
}
shutdownTimeout, err := durationFromEnv(
"SHUTDOWN_TIMEOUT",
10*time.Second,
)
if err != nil {
return Config{}, err
}
if databaseMinConns > databaseMaxConns {
return Config{}, errors.New(
"DB_MIN_CONNS must not be greater than DB_MAX_CONNS",
)
}
if idempotencyTTL < 24*time.Hour {
return Config{}, errors.New(
"IDEMPOTENCY_TTL_SECONDS must be at least 86400",
)
}
if shutdownDrainDelay >= shutdownTimeout {
return Config{}, errors.New(
"SHUTDOWN_DRAIN_DELAY must be less than SHUTDOWN_TIMEOUT",
)
}
if jobRetryMax < jobRetryBase {
return Config{}, errors.New("JOB_RETRY_MAX must not be less than JOB_RETRY_BASE")
}
if jobLease <= jobTimeout {
return Config{}, errors.New("JOB_LEASE_SECONDS must be greater than JOB_TIMEOUT_SECONDS")
}
return Config{
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
HTTPPort: envOrDefault("APP_PORT", "8080"),
InstanceID: instanceID,
SessionTTL: sessionTTL,
IdempotencyTTL: idempotencyTTL,
SessionCookieSecure: sessionCookieSecure,
CursorSigningKey: cursorSigningKey,
LoginRateLimit: int(loginRateLimit),
LoginRateWindow: loginRateWindow,
DatabaseURL: databaseURL,
DatabaseMaxConns: databaseMaxConns,
DatabaseMinConns: databaseMinConns,
DatabaseMaxConnLifetime: databaseMaxConnLifetime,
DatabaseMaxConnIdleTime: databaseMaxConnIdleTime,
DatabaseHealthCheckPeriod: databaseHealthCheckPeriod,
DatabaseConnectTimeout: databaseConnectTimeout,
DatabaseQueryTimeout: databaseQueryTimeout,
RedisURL: redisURL,
RedisCacheTTL: redisCacheTTL,
RedisOperationTimeout: redisOperationTimeout,
RedisPoolSize: int(redisPoolSize),
S3Endpoint: envOrDefault("S3_ENDPOINT", "http://minio:9000"),
S3Region: envOrDefault("S3_REGION", "us-east-1"),
S3Bucket: envOrDefault("S3_BUCKET", "messenger-attachments"),
S3AccessKeyID: s3AccessKeyID,
S3SecretAccessKey: s3SecretAccessKey,
S3OperationTimeout: s3OperationTimeout,
BrokerURL: brokerURL,
WorkerConcurrency: int(workerConcurrency),
JobMaxAttempts: int(jobMaxAttempts),
JobTimeout: jobTimeout,
JobRetryBase: jobRetryBase,
JobRetryMax: jobRetryMax,
JobLease: jobLease,
StagingRetention: stagingRetention,
StagingCleanupInterval: stagingCleanupInterval,
ReadinessTimeout: readinessTimeout,
ShutdownDrainDelay: shutdownDrainDelay,
ShutdownTimeout: shutdownTimeout,
}, nil
}
var instanceIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
func instanceIDFromEnv() (string, error) {
instanceID := strings.TrimSpace(os.Getenv("INSTANCE_ID"))
if instanceID == "" {
randomBytes := make([]byte, 6)
if _, err := rand.Read(randomBytes); err != nil {
return "", fmt.Errorf("generate opaque instance id: %w", err)
}
instanceID = "api-" + hex.EncodeToString(randomBytes)
}
if !instanceIDPattern.MatchString(instanceID) {
return "", errors.New(
"INSTANCE_ID or hostname must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}",
)
}
return instanceID, nil
}
func (c Config) HTTPAddress() string {
return net.JoinHostPort(c.HTTPHost, c.HTTPPort)
}
func roleValueOrFile(required bool, valueEnv, fileEnv string) (string, error) {
if required {
return requiredValueOrFile(valueEnv, fileEnv)
}
return optionalValueOrFile(valueEnv, fileEnv)
}
func requiredValueOrFile(valueEnv, fileEnv string) (string, error) {
value, valueExists := os.LookupEnv(valueEnv)
filePath, fileExists := os.LookupEnv(fileEnv)
if valueExists && fileExists {
return "", fmt.Errorf(
"%s and %s must not be set at the same time",
valueEnv,
fileEnv,
)
}
if valueExists {
value = strings.TrimSpace(value)
if value == "" {
return "", fmt.Errorf("%s must not be empty", valueEnv)
}
return value, nil
}
if fileExists {
filePath = strings.TrimSpace(filePath)
if filePath == "" {
return "", fmt.Errorf("%s must not be empty", fileEnv)
}
data, err := os.ReadFile(filePath)
if err != nil {
return "", fmt.Errorf("read %s: %w", fileEnv, err)
}
value = strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
}
return value, nil
}
return "", fmt.Errorf("%s or %s must be set", valueEnv, fileEnv)
}
func optionalValueOrFile(valueEnv, fileEnv string) (string, error) {
value, valueExists := os.LookupEnv(valueEnv)
filePath, fileExists := os.LookupEnv(fileEnv)
if valueExists && fileExists {
return "", fmt.Errorf(
"%s and %s must not be set at the same time",
valueEnv,
fileEnv,
)
}
if valueExists {
value = strings.TrimSpace(value)
if value == "" {
return "", fmt.Errorf("%s must not be empty", valueEnv)
}
return value, nil
}
if fileExists {
filePath = strings.TrimSpace(filePath)
if filePath == "" {
return "", fmt.Errorf("%s must not be empty", fileEnv)
}
data, err := os.ReadFile(filePath)
if err != nil {
return "", fmt.Errorf("read %s: %w", fileEnv, err)
}
value = strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
}
return value, nil
}
return "", nil
}
func envOrDefault(name, fallback string) string {
value := strings.TrimSpace(os.Getenv(name))
if value == "" {
return fallback
}
return value
}
func int32FromEnv(name string, fallback, minimum int32) (int32, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback, nil
}
value, err := strconv.ParseInt(raw, 10, 32)
if err != nil {
return 0, fmt.Errorf("%s must be an integer: %w", name, err)
}
if value < int64(minimum) {
return 0, fmt.Errorf("%s must be at least %d", name, minimum)
}
return int32(value), nil
}
func boolFromEnv(name string, fallback bool) (bool, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback, nil
}
value, err := strconv.ParseBool(raw)
if err != nil {
return false, fmt.Errorf("%s must be true or false: %w", name, err)
}
return value, nil
}
func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
return fallback, nil
}
value, err := time.ParseDuration(raw)
if err != nil {
return 0, fmt.Errorf(
"%s must be a Go duration such as 3s or 5m: %w",
name,
err,
)
}
if value <= 0 {
return 0, fmt.Errorf("%s must be positive", name)
}
return value, nil
}
func secondsDurationFromEnv(
name string,
fallbackSeconds int64,
) (time.Duration, error) {
raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
raw = strconv.FormatInt(fallbackSeconds, 10)
}
seconds, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return 0, fmt.Errorf(
"%s must be an integer number of seconds: %w",
name,
err,
)
}
if seconds <= 0 {
return 0, fmt.Errorf("%s must be positive", name)
}
duration, err := time.ParseDuration(raw + "s")
if err != nil {
return 0, fmt.Errorf("%s is too large: %w", name, err)
}
return duration, nil
}
+35
View File
@@ -0,0 +1,35 @@
package config
import "testing"
func TestInstanceIDFromEnvironment(t *testing.T) {
t.Setenv("INSTANCE_ID", "api-replica_01")
instanceID, err := instanceIDFromEnv()
if err != nil {
t.Fatal(err)
}
if instanceID != "api-replica_01" {
t.Fatalf("got %q, want api-replica_01", instanceID)
}
}
func TestInstanceIDRejectsUnsafeHeaderValue(t *testing.T) {
t.Setenv("INSTANCE_ID", "api-1\r\nX-Forged: true")
if _, err := instanceIDFromEnv(); err == nil {
t.Fatal("expected unsafe instance ID to be rejected")
}
}
func TestInstanceIDGeneratesOpaqueAlias(t *testing.T) {
t.Setenv("INSTANCE_ID", "")
instanceID, err := instanceIDFromEnv()
if err != nil {
t.Fatal(err)
}
if instanceID == "" {
t.Fatal("random alias returned an empty instance ID")
}
}
+29
View File
@@ -0,0 +1,29 @@
package config
import "testing"
func TestBoolFromEnv(t *testing.T) {
t.Run("fallback", func(t *testing.T) {
t.Setenv("TEST_BOOL", "")
value, err := boolFromEnv("TEST_BOOL", true)
if err != nil || !value {
t.Fatalf("boolFromEnv() = %v, %v; want true, nil", value, err)
}
})
t.Run("explicit false", func(t *testing.T) {
t.Setenv("TEST_BOOL", "false")
value, err := boolFromEnv("TEST_BOOL", true)
if err != nil || value {
t.Fatalf("boolFromEnv() = %v, %v; want false, nil", value, err)
}
})
t.Run("invalid", func(t *testing.T) {
t.Setenv("TEST_BOOL", "sometimes")
_, err := boolFromEnv("TEST_BOOL", false)
if err == nil {
t.Fatal("boolFromEnv() error = nil, want validation error")
}
})
}
+41
View File
@@ -0,0 +1,41 @@
package database
import (
"context"
"fmt"
"mtusi2026lab7/internal/config"
"github.com/jackc/pgx/v5/pgxpool"
)
func Open(
ctx context.Context,
cfg config.Config,
) (*pgxpool.Pool, error) {
poolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL)
if err != nil {
return nil, fmt.Errorf("parse PostgreSQL configuration: %w", err)
}
poolConfig.MaxConns = cfg.DatabaseMaxConns
poolConfig.MinConns = cfg.DatabaseMinConns
poolConfig.MaxConnLifetime = cfg.DatabaseMaxConnLifetime
poolConfig.MaxConnIdleTime = cfg.DatabaseMaxConnIdleTime
poolConfig.HealthCheckPeriod = cfg.DatabaseHealthCheckPeriod
poolConfig.ConnConfig.Tracer = pgxQueryTracer{}
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
}
// NewWithConfig создаёт структуру пула, но не гарантирует,
// что PostgreSQL уже доступен. Ping обеспечивает fail-fast.
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping PostgreSQL: %w", err)
}
return pool, nil
}
+92
View File
@@ -0,0 +1,92 @@
package database
import (
"context"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
type pgxQueryTracer struct{}
func (pgxQueryTracer) TraceAcquireStart(
ctx context.Context,
_ *pgxpool.Pool,
_ pgxpool.TraceAcquireStartData,
) context.Context {
ctx, _ = otel.Tracer("mtusi2026lab7/postgresql").Start(
ctx,
"postgresql.acquire",
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
attribute.String("db.system.name", "postgresql"),
attribute.String("db.operation.name", "ACQUIRE"),
),
)
return ctx
}
func (pgxQueryTracer) TraceAcquireEnd(
ctx context.Context,
_ *pgxpool.Pool,
data pgxpool.TraceAcquireEndData,
) {
span := trace.SpanFromContext(ctx)
if data.Err != nil {
span.SetStatus(codes.Error, "database connection acquisition failed")
} else {
span.SetStatus(codes.Ok, "")
}
span.End()
}
func (pgxQueryTracer) TraceQueryStart(
ctx context.Context,
_ *pgx.Conn,
data pgx.TraceQueryStartData,
) context.Context {
operation := databaseOperation(data.SQL)
ctx, _ = otel.Tracer("mtusi2026lab7/postgresql").Start(
ctx,
"postgresql."+strings.ToLower(operation),
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
attribute.String("db.system.name", "postgresql"),
attribute.String("db.operation.name", operation),
),
)
return ctx
}
func (pgxQueryTracer) TraceQueryEnd(
ctx context.Context,
_ *pgx.Conn,
data pgx.TraceQueryEndData,
) {
span := trace.SpanFromContext(ctx)
if data.Err != nil {
span.SetStatus(codes.Error, "database operation failed")
} else {
span.SetStatus(codes.Ok, "")
}
span.End()
}
func databaseOperation(sql string) string {
fields := strings.Fields(sql)
if len(fields) == 0 {
return "QUERY"
}
operation := strings.ToUpper(fields[0])
switch operation {
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK":
return operation
default:
return "QUERY"
}
}
+126
View File
@@ -0,0 +1,126 @@
package domain
import (
"encoding/hex"
"fmt"
"strings"
"time"
"unicode"
"unicode/utf8"
)
const (
MaxAttachmentFilenameCodePoints = 255
MaxAttachmentSizeBytes = 10 * 1024 * 1024
MaxAttachmentPixels = 40_000_000
)
type AttachmentVariant struct {
Name string
ContentType string
SizeBytes int64
Width int
Height int
SHA256 string
ObjectKey string
PipelineVersion int
}
type AttachmentStatus string
const (
AttachmentStatusQueued AttachmentStatus = "queued"
AttachmentStatusProcessing AttachmentStatus = "processing"
AttachmentStatusReady AttachmentStatus = "ready"
AttachmentStatusFailed AttachmentStatus = "failed"
// Source-compatible alias for the lab4 reconciliation code.
AttachmentStatusPending = AttachmentStatusQueued
)
// Attachment contains metadata only. ObjectKey points to bytes in the
// private object store and must never be derived from Filename.
type Attachment struct {
ID string
ChatID string
OwnerID string
Filename string
ObjectKey string
ContentType string
SizeBytes int64
SHA256 string
Width int
Height int
StagingKey string
PipelineVersion int
Status AttachmentStatus
Variants []AttachmentVariant
ErrorCode *string
CreatedAt time.Time
UpdatedAt time.Time
}
func ValidateAttachmentFilename(filename string) error {
if !utf8.ValidString(filename) {
return fmt.Errorf("filename must be valid UTF-8")
}
filenameLength := utf8.RuneCountInString(filename)
if filenameLength < 1 || filenameLength > MaxAttachmentFilenameCodePoints {
return fmt.Errorf("filename length must be between 1 and %d code points", MaxAttachmentFilenameCodePoints)
}
if strings.TrimSpace(filename) == "" || filename == "." || filename == ".." {
return fmt.Errorf("filename is unsafe")
}
if strings.ContainsAny(filename, `/\\`) {
return fmt.Errorf("filename must not contain path separators")
}
for _, character := range filename {
if unicode.IsControl(character) {
return fmt.Errorf("filename must not contain control characters")
}
}
return nil
}
func ValidateAttachmentContentType(contentType string) error {
if contentType != "image/png" && contentType != "image/jpeg" {
return fmt.Errorf("content type must be image/png or image/jpeg")
}
return nil
}
// ValidateReadyAttachmentMetadata checks the bounded metadata produced after
// the upload stream has been identified, decoded and hashed. It deliberately
// does not trust an HTTP Content-Type header.
func ValidateReadyAttachmentMetadata(
filename string,
contentType string,
sizeBytes int64,
sha256Hex string,
width int,
height int,
) error {
if err := ValidateAttachmentFilename(filename); err != nil {
return err
}
if err := ValidateAttachmentContentType(contentType); err != nil {
return err
}
if sizeBytes < 1 || sizeBytes > MaxAttachmentSizeBytes {
return fmt.Errorf("attachment size must be between 1 and %d bytes", MaxAttachmentSizeBytes)
}
if width < 1 || height < 1 {
return fmt.Errorf("image dimensions must be positive and contain at most %d pixels", MaxAttachmentPixels)
}
if int64(width) > int64(MaxAttachmentPixels)/int64(height) {
return fmt.Errorf("image dimensions must be positive and contain at most %d pixels", MaxAttachmentPixels)
}
if len(sha256Hex) != 64 || sha256Hex != strings.ToLower(sha256Hex) {
return fmt.Errorf("sha256 must contain 64 lowercase hexadecimal characters")
}
decodedHash, err := hex.DecodeString(sha256Hex)
if err != nil || len(decodedHash) != 32 {
return fmt.Errorf("sha256 must contain 64 lowercase hexadecimal characters")
}
return nil
}
+57
View File
@@ -0,0 +1,57 @@
package domain
import "time"
const AttachmentJobType = "attachment.process.v1"
type AttachmentJobStatus string
const (
AttachmentJobQueued AttachmentJobStatus = "queued"
AttachmentJobProcessing AttachmentJobStatus = "processing"
AttachmentJobSucceeded AttachmentJobStatus = "succeeded"
AttachmentJobFailed AttachmentJobStatus = "failed"
AttachmentJobSuperseded AttachmentJobStatus = "superseded"
)
type AttachmentJob struct {
SchemaVersion int
JobID string
Type string
AttachmentID string
PipelineVersion int
Attempt int
MaxAttempts int
Status AttachmentJobStatus
ErrorCode *string
AvailableAt time.Time
LeaseUntil *time.Time
LeasedBy *string
ReplayCount int
CreatedAt time.Time
UpdatedAt time.Time
TraceParent string
TraceState string
}
type AttachmentJobMessage struct {
SchemaVersion int `json:"schema_version"`
JobID string `json:"job_id"`
Type string `json:"type"`
AttachmentID string `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt time.Time `json:"created_at"`
}
func (job AttachmentJob) Message() AttachmentJobMessage {
return AttachmentJobMessage{
SchemaVersion: job.SchemaVersion,
JobID: job.JobID,
Type: job.Type,
AttachmentID: job.AttachmentID,
PipelineVersion: job.PipelineVersion,
Attempt: job.Attempt,
CreatedAt: job.CreatedAt.UTC(),
}
}
+59
View File
@@ -0,0 +1,59 @@
package domain
import (
"math"
"strings"
"testing"
)
func TestValidateReadyAttachmentMetadata(t *testing.T) {
validHash := strings.Repeat("ab", 32)
testCases := []struct {
name string
filename string
contentType string
sizeBytes int64
sha256 string
width int
height int
wantError bool
}{
{name: "png", filename: "кот.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1},
{name: "jpeg at limits", filename: strings.Repeat("界", 255), contentType: "image/jpeg", sizeBytes: MaxAttachmentSizeBytes, sha256: validHash, width: 8_000, height: 5_000},
{name: "empty filename", filename: "", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "blank filename", filename: " ", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "dot segment", filename: "..", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "forward slash", filename: "folder/image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "backslash", filename: `folder\\image.png`, contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "control character", filename: "image\n.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "C1 control character", filename: "image\u0085.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "invalid UTF-8", filename: string([]byte{'x', 0xff, '.', 'p', 'n', 'g'}), contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "filename too long", filename: strings.Repeat("a", 256), contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "unsupported MIME", filename: "image.gif", contentType: "image/gif", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "empty file", filename: "image.png", contentType: "image/png", sizeBytes: 0, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "file too large", filename: "image.png", contentType: "image/png", sizeBytes: MaxAttachmentSizeBytes + 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "zero width", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 0, height: 1, wantError: true},
{name: "too many pixels", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 8_001, height: 5_000, wantError: true},
{name: "dimension multiplication cannot overflow", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: math.MaxInt, height: math.MaxInt, wantError: true},
{name: "short hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: "ab", width: 1, height: 1, wantError: true},
{name: "uppercase hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: strings.ToUpper(validHash), width: 1, height: 1, wantError: true},
{name: "non-hex hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: strings.Repeat("zz", 32), width: 1, height: 1, wantError: true},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := ValidateReadyAttachmentMetadata(
testCase.filename,
testCase.contentType,
testCase.sizeBytes,
testCase.sha256,
testCase.width,
testCase.height,
)
if (err != nil) != testCase.wantError {
t.Fatalf("ValidateReadyAttachmentMetadata() error = %v, wantError %v", err, testCase.wantError)
}
})
}
}
+21
View File
@@ -0,0 +1,21 @@
package domain
import "time"
type Chat struct {
ID string
Title string
MemberIDs []string
CreatedAt time.Time
}
type ChatCursor struct {
CreatedAt time.Time
ChatID string
UserID string
}
type ChatPage struct {
Items []Chat
NextCursor *string
}
+8
View File
@@ -0,0 +1,8 @@
package domain
import "errors"
var (
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
)
+23
View File
@@ -0,0 +1,23 @@
package domain
import "time"
type Message struct {
ID string
ChatID string
SenderID string
Text string
AttachmentIDs []string
CreatedAt time.Time
}
type MessageCursor struct {
CreatedAt time.Time
MessageID string
ChatID string
}
type MessagePage struct {
Items []Message
NextCursor *string
}
+70
View File
@@ -0,0 +1,70 @@
package domain
import (
"strings"
"testing"
)
func TestValidateMessageInput(t *testing.T) {
validAttachment := "11111111-1111-4111-8111-111111111111"
testCases := []struct {
name string
text string
attachmentIDs []string
wantError bool
}{
{name: "text only", text: "hello"},
{name: "attachment only", attachmentIDs: []string{validAttachment}},
{name: "whitespace with attachment", text: " ", attachmentIDs: []string{validAttachment}},
{name: "empty", wantError: true},
{name: "whitespace only", text: " ", wantError: true},
{name: "text too long", text: strings.Repeat("界", 4001), wantError: true},
{name: "invalid attachment uuid", text: "hello", attachmentIDs: []string{"not-a-uuid"}, wantError: true},
{
name: "duplicate attachment uuid ignores case",
text: "hello",
attachmentIDs: []string{
"AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA",
"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
},
wantError: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := ValidateMessageInput(testCase.text, testCase.attachmentIDs)
if (err != nil) != testCase.wantError {
t.Fatalf("ValidateMessageInput() error = %v, wantError %v", err, testCase.wantError)
}
})
}
}
func TestValidateMessageInputAttachmentLimit(t *testing.T) {
attachmentIDs := []string{
"00000000-0000-4000-8000-000000000001",
"00000000-0000-4000-8000-000000000002",
"00000000-0000-4000-8000-000000000003",
"00000000-0000-4000-8000-000000000004",
"00000000-0000-4000-8000-000000000005",
"00000000-0000-4000-8000-000000000006",
"00000000-0000-4000-8000-000000000007",
"00000000-0000-4000-8000-000000000008",
"00000000-0000-4000-8000-000000000009",
"00000000-0000-4000-8000-000000000010",
}
if err := ValidateMessageInput("", attachmentIDs); err != nil {
t.Fatalf("10 attachments must be accepted: %v", err)
}
attachmentIDs = append(
attachmentIDs,
"00000000-0000-4000-8000-000000000011",
)
if err := ValidateMessageInput("hello", attachmentIDs); err == nil {
t.Fatal("11 attachments must be rejected")
}
}
+10
View File
@@ -0,0 +1,10 @@
package domain
import "time"
type Session struct {
Token string
TokenType string
ExpiresAt time.Time
User User
}
+11
View File
@@ -0,0 +1,11 @@
package domain
import "time"
// User is the transport-independent representation of a messenger user.
type User struct {
ID string
Username string
DisplayName string
CreatedAt time.Time
}
+101
View File
@@ -0,0 +1,101 @@
package domain
import (
"fmt"
"regexp"
"strings"
"unicode/utf8"
"github.com/google/uuid"
)
const MaxMessageAttachments = 10
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func ValidateUser(username, displayName string) error {
if !usernameRegex.MatchString(username) {
return fmt.Errorf("username must match [a-z0-9_]{3,32}")
}
nameRunes := utf8.RuneCountInString(displayName)
if nameRunes < 1 || nameRunes > 100 {
return fmt.Errorf("display_name length must be between 1 and 100 code points")
}
if strings.TrimSpace(displayName) == "" {
return fmt.Errorf("display_name cannot be only whitespace")
}
return nil
}
// Validate remains as a compatibility convenience for existing callers.
func (u User) Validate() error {
return ValidateUser(u.Username, u.DisplayName)
}
func ValidateChatInput(title string, memberIDs []string, callerID string) error {
titleRunes := utf8.RuneCountInString(title)
if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" {
return fmt.Errorf("invalid chat title")
}
if len(memberIDs) == 0 {
return fmt.Errorf("member_ids cannot be empty")
}
if len(memberIDs) > 100 {
return fmt.Errorf("member_ids must contain at most 100 users")
}
hasCaller := false
seen := make(map[string]struct{}, len(memberIDs))
for _, id := range memberIDs {
if _, err := uuid.Parse(id); err != nil {
return fmt.Errorf("invalid member uuid: %s", id)
}
if _, exists := seen[id]; exists {
return fmt.Errorf("duplicate member_id: %s", id)
}
seen[id] = struct{}{}
if id == callerID {
hasCaller = true
}
}
if !hasCaller {
return fmt.Errorf("caller must be in member_ids")
}
return nil
}
func ValidateMessageInput(text string, attachmentIDs []string) error {
textRunes := utf8.RuneCountInString(text)
if textRunes > 4000 {
return fmt.Errorf("message text length must be at most 4000 code points")
}
if len(attachmentIDs) > MaxMessageAttachments {
return fmt.Errorf("attachment_ids must contain at most %d items", MaxMessageAttachments)
}
seen := make(map[string]struct{}, len(attachmentIDs))
for _, attachmentID := range attachmentIDs {
parsedID, err := uuid.Parse(attachmentID)
if err != nil {
return fmt.Errorf("invalid attachment uuid: %s", attachmentID)
}
canonicalID := parsedID.String()
if _, exists := seen[canonicalID]; exists {
return fmt.Errorf("duplicate attachment_id: %s", attachmentID)
}
seen[canonicalID] = struct{}{}
}
if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 {
return fmt.Errorf("message must contain non-blank text or at least one attachment")
}
return nil
}
// ValidateMessageText remains for callers that create text-only messages.
func ValidateMessageText(text string) error {
return ValidateMessageInput(text, nil)
}
+203
View File
@@ -0,0 +1,203 @@
package reconcile
import (
"context"
"fmt"
"sort"
"time"
"mtusi2026lab7/internal/adapter/objectstore"
"mtusi2026lab7/internal/domain"
)
const (
IssueOrphanObject = "orphan_object"
IssueMissingObject = "missing_object"
IssueFailedObject = "failed_object"
IssueReferencedMissing = "referenced_missing_object"
)
type AttachmentRecord struct {
ID string
ObjectKey string
AdditionalObjectKeys []string
Status domain.AttachmentStatus
UpdatedAt time.Time
Referenced bool
}
type MetadataStore interface {
ListAttachmentInventory(ctx context.Context) ([]AttachmentRecord, error)
MarkAttachmentFailedIfUnreferenced(
ctx context.Context,
attachmentID string,
expectedStatus domain.AttachmentStatus,
updatedBefore time.Time,
errorCode string,
updatedAt time.Time,
) (bool, error)
}
type ObjectInventory interface {
List(ctx context.Context, prefix string) ([]objectstore.StoredObject, error)
Delete(ctx context.Context, key string) error
}
type Issue struct {
Kind string `json:"kind"`
AttachmentID string `json:"attachment_id,omitempty"`
ObjectKey string `json:"object_key"`
Protected bool `json:"protected,omitempty"`
Action string `json:"action"`
}
type Result struct {
DryRun bool `json:"dry_run"`
GracePeriod time.Duration `json:"-"`
GracePeriodSeconds int64 `json:"grace_period_seconds"`
ScannedAttachments int `json:"scanned_attachments"`
ScannedObjects int `json:"scanned_objects"`
Issues []Issue `json:"issues"`
DeletedObjects int `json:"deleted_objects"`
FailedAttachments int `json:"failed_attachments"`
Duration time.Duration `json:"-"`
DurationMillis int64 `json:"duration_ms"`
}
type Reconciler struct {
metadata MetadataStore
objects ObjectInventory
now func() time.Time
}
func New(metadata MetadataStore, objects ObjectInventory) (*Reconciler, error) {
if metadata == nil || objects == nil {
return nil, fmt.Errorf("metadata and object stores are required")
}
return &Reconciler{
metadata: metadata,
objects: objects,
now: func() time.Time { return time.Now().UTC() },
}, nil
}
func (r *Reconciler) Run(
ctx context.Context,
gracePeriod time.Duration,
apply bool,
) (Result, error) {
if gracePeriod <= 0 {
return Result{}, fmt.Errorf("grace period must be positive")
}
startedAt := r.now().UTC()
cutoff := startedAt.Add(-gracePeriod)
result := Result{
DryRun: !apply,
GracePeriod: gracePeriod,
GracePeriodSeconds: int64(gracePeriod / time.Second),
Issues: make([]Issue, 0),
}
attachments, err := r.metadata.ListAttachmentInventory(ctx)
if err != nil {
return Result{}, fmt.Errorf("list attachment metadata: %w", err)
}
objects, err := r.objects.List(ctx, "attachments/")
if err != nil {
return Result{}, fmt.Errorf("list attachment objects: %w", err)
}
result.ScannedAttachments = len(attachments)
result.ScannedObjects = len(objects)
attachmentsByKey := make(map[string]AttachmentRecord, len(attachments))
for _, attachment := range attachments {
attachmentsByKey[attachment.ObjectKey] = attachment
for _, objectKey := range attachment.AdditionalObjectKeys {
if objectKey != "" {
attachmentsByKey[objectKey] = attachment
}
}
}
objectsByKey := make(map[string]objectstore.StoredObject, len(objects))
for _, object := range objects {
objectsByKey[object.Key] = object
if _, exists := attachmentsByKey[object.Key]; exists {
continue
}
if object.LastModified.IsZero() || object.LastModified.After(cutoff) {
continue
}
issue := Issue{Kind: IssueOrphanObject, ObjectKey: object.Key, Action: "would_delete"}
if apply {
if err = r.objects.Delete(ctx, object.Key); err != nil {
return result, fmt.Errorf("delete orphan object %q: %w", object.Key, err)
}
issue.Action = "deleted"
result.DeletedObjects++
}
result.Issues = append(result.Issues, issue)
}
for _, attachment := range attachments {
if attachment.UpdatedAt.After(cutoff) {
continue
}
_, objectExists := objectsByKey[attachment.ObjectKey]
switch {
case attachment.Status == domain.AttachmentStatusReady && !objectExists:
issue := Issue{
Kind: IssueMissingObject,
AttachmentID: attachment.ID,
ObjectKey: attachment.ObjectKey,
Protected: attachment.Referenced,
Action: "would_mark_failed",
}
if attachment.Referenced {
issue.Kind = IssueReferencedMissing
issue.Action = "manual_repair_required"
} else if apply {
changed, markError := r.metadata.MarkAttachmentFailedIfUnreferenced(
ctx, attachment.ID, attachment.Status, cutoff,
"reconciler_missing_object", startedAt,
)
if markError != nil {
return result, fmt.Errorf("mark missing attachment %q failed: %w", attachment.ID, markError)
}
if changed {
issue.Action = "marked_failed"
result.FailedAttachments++
} else {
issue.Action = "skipped_concurrent_change"
}
}
result.Issues = append(result.Issues, issue)
case attachment.Status == domain.AttachmentStatusFailed && objectExists:
issue := Issue{
Kind: IssueFailedObject, AttachmentID: attachment.ID,
ObjectKey: attachment.ObjectKey, Protected: attachment.Referenced,
Action: "would_delete",
}
if attachment.Referenced {
issue.Action = "manual_repair_required"
} else if apply {
if err = r.objects.Delete(ctx, attachment.ObjectKey); err != nil {
return result, fmt.Errorf("delete failed attachment object %q: %w", attachment.ObjectKey, err)
}
issue.Action = "deleted"
result.DeletedObjects++
}
result.Issues = append(result.Issues, issue)
}
}
sort.Slice(result.Issues, func(i, j int) bool {
if result.Issues[i].ObjectKey == result.Issues[j].ObjectKey {
return result.Issues[i].Kind < result.Issues[j].Kind
}
return result.Issues[i].ObjectKey < result.Issues[j].ObjectKey
})
result.Duration = r.now().UTC().Sub(startedAt)
result.DurationMillis = result.Duration.Milliseconds()
return result, nil
}
+228
View File
@@ -0,0 +1,228 @@
package reconcile
import (
"context"
"errors"
"testing"
"time"
"mtusi2026lab7/internal/adapter/objectstore"
"mtusi2026lab7/internal/domain"
)
type fakeMetadataStore struct {
records []AttachmentRecord
markError error
skipMark bool
}
func (store *fakeMetadataStore) ListAttachmentInventory(
context.Context,
) ([]AttachmentRecord, error) {
return append([]AttachmentRecord(nil), store.records...), nil
}
func (store *fakeMetadataStore) MarkAttachmentFailedIfUnreferenced(
_ context.Context,
attachmentID string,
expectedStatus domain.AttachmentStatus,
updatedBefore time.Time,
errorCode string,
updatedAt time.Time,
) (bool, error) {
if store.markError != nil {
return false, store.markError
}
if store.skipMark {
return false, nil
}
for index := range store.records {
record := &store.records[index]
if record.ID != attachmentID || record.Status != expectedStatus ||
record.UpdatedAt.After(updatedBefore) || record.Referenced {
continue
}
record.Status = domain.AttachmentStatusFailed
record.UpdatedAt = updatedAt
_ = errorCode
return true, nil
}
return false, nil
}
func TestReconcilerDoesNotTouchActiveAttachments(t *testing.T) {
old := time.Now().UTC().Add(-2 * time.Hour)
metadata := &fakeMetadataStore{
records: []AttachmentRecord{
{
ID: "queued-old", ObjectKey: "attachments/queued-old",
AdditionalObjectKeys: []string{"attachments/queued-old-staging"},
Status: domain.AttachmentStatusQueued, UpdatedAt: old,
},
{
ID: "processing-old", ObjectKey: "attachments/processing-old",
Status: domain.AttachmentStatusProcessing, UpdatedAt: old,
},
},
}
objects := &fakeObjectInventory{objects: map[string]objectstore.StoredObject{
"attachments/queued-old": {Key: "attachments/queued-old", LastModified: old},
"attachments/queued-old-staging": {Key: "attachments/queued-old-staging", LastModified: old},
"attachments/processing-old": {Key: "attachments/processing-old", LastModified: old},
}}
reconciler, err := New(metadata, objects)
if err != nil {
t.Fatal(err)
}
result, err := reconciler.Run(context.Background(), time.Hour, true)
if err != nil {
t.Fatal(err)
}
if result.DeletedObjects != 0 || result.FailedAttachments != 0 {
t.Fatalf("active attachments must not be reconciled as stale: %+v", result)
}
if len(result.Issues) != 0 {
t.Fatalf("active attachments must not produce reconciliation issues: %+v", result.Issues)
}
if len(objects.objects) != 3 {
t.Fatal("reconciler deleted an object belonging to an active attachment")
}
}
type fakeObjectInventory struct {
objects map[string]objectstore.StoredObject
deleteError error
}
func (store *fakeObjectInventory) List(
context.Context,
string,
) ([]objectstore.StoredObject, error) {
objects := make([]objectstore.StoredObject, 0, len(store.objects))
for _, object := range store.objects {
objects = append(objects, object)
}
return objects, nil
}
func (store *fakeObjectInventory) Delete(_ context.Context, key string) error {
if store.deleteError != nil {
return store.deleteError
}
delete(store.objects, key)
return nil
}
func TestReconcilerDryRunApplyAndRepeat(t *testing.T) {
now := time.Now().UTC()
old := now.Add(-2 * time.Hour)
fresh := now.Add(-5 * time.Minute)
metadata := &fakeMetadataStore{records: []AttachmentRecord{
{
ID: "ready-present", ObjectKey: "attachments/ready-present",
AdditionalObjectKeys: []string{"attachments/ready-present-thumbnail"},
Status: domain.AttachmentStatusReady, UpdatedAt: old,
},
{ID: "ready-missing", ObjectKey: "attachments/ready-missing", Status: domain.AttachmentStatusReady, UpdatedAt: old},
{ID: "ready-used-missing", ObjectKey: "attachments/ready-used-missing", Status: domain.AttachmentStatusReady, UpdatedAt: old, Referenced: true},
{ID: "queued-old", ObjectKey: "attachments/queued-old", Status: domain.AttachmentStatusQueued, UpdatedAt: old},
{ID: "failed-old", ObjectKey: "attachments/failed-old", Status: domain.AttachmentStatusFailed, UpdatedAt: old},
{ID: "queued-fresh", ObjectKey: "attachments/queued-fresh", Status: domain.AttachmentStatusQueued, UpdatedAt: fresh},
}}
objects := &fakeObjectInventory{objects: map[string]objectstore.StoredObject{
"attachments/ready-present": {Key: "attachments/ready-present", LastModified: old},
"attachments/ready-present-thumbnail": {Key: "attachments/ready-present-thumbnail", LastModified: old},
"attachments/queued-old": {Key: "attachments/queued-old", LastModified: old},
"attachments/failed-old": {Key: "attachments/failed-old", LastModified: old},
"attachments/orphan-old": {Key: "attachments/orphan-old", LastModified: old},
"attachments/orphan-fresh": {Key: "attachments/orphan-fresh", LastModified: fresh},
}}
reconciler, err := New(metadata, objects)
if err != nil {
t.Fatal(err)
}
dryRun, err := reconciler.Run(context.Background(), time.Hour, false)
if err != nil {
t.Fatal(err)
}
if !dryRun.DryRun || len(dryRun.Issues) != 4 ||
dryRun.DeletedObjects != 0 || dryRun.FailedAttachments != 0 {
t.Fatalf("unexpected dry-run result: %+v", dryRun)
}
if len(objects.objects) != 6 {
t.Fatal("dry-run changed object storage")
}
for _, record := range metadata.records {
if record.ID == "ready-missing" && record.Status != domain.AttachmentStatusReady {
t.Fatal("dry-run changed metadata")
}
}
applied, err := reconciler.Run(context.Background(), time.Hour, true)
if err != nil {
t.Fatal(err)
}
if applied.DeletedObjects != 2 || applied.FailedAttachments != 1 {
t.Fatalf("unexpected apply result: %+v", applied)
}
if _, exists := objects.objects["attachments/orphan-old"]; exists {
t.Fatal("old orphan was not deleted")
}
if _, exists := objects.objects["attachments/orphan-fresh"]; !exists {
t.Fatal("fresh orphan must be protected by grace period")
}
if _, exists := objects.objects["attachments/ready-present"]; !exists {
t.Fatal("healthy object was deleted")
}
if _, exists := objects.objects["attachments/ready-present-thumbnail"]; !exists {
t.Fatal("managed variant object was deleted as an orphan")
}
if _, exists := objects.objects["attachments/queued-old"]; !exists {
t.Fatal("active queued attachment object was deleted")
}
for _, issue := range applied.Issues {
if issue.AttachmentID == "ready-used-missing" &&
(!issue.Protected || issue.Action != "manual_repair_required") {
t.Fatalf("referenced attachment was not protected: %+v", issue)
}
}
repeated, err := reconciler.Run(context.Background(), time.Hour, true)
if err != nil {
t.Fatal(err)
}
if repeated.DeletedObjects != 0 || repeated.FailedAttachments != 0 {
t.Fatalf("repeat must be mutation-idempotent: %+v", repeated)
}
if len(repeated.Issues) != 1 || !repeated.Issues[0].Protected {
t.Fatalf("repeat should retain only protected manual issue: %+v", repeated)
}
}
func TestReconcilerReportsMutationFailures(t *testing.T) {
old := time.Now().UTC().Add(-2 * time.Hour)
metadata := &fakeMetadataStore{records: []AttachmentRecord{
{ID: "missing", ObjectKey: "attachments/missing", Status: domain.AttachmentStatusReady, UpdatedAt: old},
}}
metadata.markError = errors.New("injected database failure")
objects := &fakeObjectInventory{objects: make(map[string]objectstore.StoredObject)}
reconciler, err := New(metadata, objects)
if err != nil {
t.Fatal(err)
}
if _, err = reconciler.Run(context.Background(), time.Hour, true); err == nil {
t.Fatal("injected database mutation failure was hidden")
}
metadata.records = nil
metadata.markError = nil
objects.objects["attachments/orphan"] = objectstore.StoredObject{
Key: "attachments/orphan", LastModified: old,
}
objects.deleteError = errors.New("injected object-store failure")
if _, err = reconciler.Run(context.Background(), time.Hour, true); err == nil {
t.Fatal("injected object-store mutation failure was hidden")
}
}
+43
View File
@@ -0,0 +1,43 @@
package security
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
"strings"
)
// ClientMTLSConfig builds a TLS 1.3 client configuration with an explicit
// workload certificate. The service name is verified against the server
// certificate; neither InsecureSkipVerify nor the host trust store is used.
func ClientMTLSConfig(caFile, certFile, keyFile, serverName string) (*tls.Config, error) {
caFile = strings.TrimSpace(caFile)
certFile = strings.TrimSpace(certFile)
keyFile = strings.TrimSpace(keyFile)
serverName = strings.TrimSpace(serverName)
if caFile == "" || certFile == "" || keyFile == "" || serverName == "" {
return nil, errors.New("client CA, certificate, key, and server name are required")
}
caPEM, err := os.ReadFile(caFile)
if err != nil {
return nil, fmt.Errorf("read client TLS CA: %w", err)
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(caPEM) {
return nil, errors.New("client TLS CA file contains no certificate")
}
certificate, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("load client TLS identity: %w", err)
}
return &tls.Config{
MinVersion: tls.VersionTLS13,
RootCAs: roots,
Certificates: []tls.Certificate{certificate},
ServerName: serverName,
}, nil
}

Some files were not shown because too many files have changed in this diff Show More