diff --git a/.dockerignore b/.dockerignore index bc16e556..a3f81508 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,20 +1,15 @@ -.git -.github -.env -.env.* -!.env.example -secrets -certs -volumes -data -backups -*.key -*.pem -*.p12 -*.pfx -*.jks -.venv -__pycache__ -node_modules -evidence -.DS_Store +** +!go.mod +!go.sum +!*.go +!migrations/ +!migrations/*.sql +!Dockerfile +!cmd/ +!cmd/load/ +!cmd/load/*.go +!requirements-dev.txt + +!Dockerfile.minio +!infra/ +!infra/s3-health.go diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..db07b85d --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +*.sh text eol=lf +*.py text eol=lf +*.go text eol=lf +*.sql text eol=lf +Dockerfile* text eol=lf diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 1bec5472..5141ca30 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,18 +1,77 @@ ## Лабораторная 4 -Автор / группа: TODO -Целевая оценка (3/4/5): TODO -Трек 5, если заявлен: TODO +**Заголовок PR:** ЛР 4 — БВТ2303 — Ситосенко — на 5 -Что реализовано и что перенесено: TODO -Команды запуска из чистого clone: TODO -Результаты проверок и ссылка на REPORT.md: TODO -Ограничения / известные ошибки: TODO -Источники и использование ИИ: TODO +- **Автор / группа:** Ситосенко / БВТ2303 +- **Целевая оценка:** 5 +- **Трек 5:** трек 2 — согласованность PostgreSQL и S3. -- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. -- [ ] Контракт и публичные тесты не ослаблены. -- [ ] make check и make test выполнены; приложен реальный вывод. -- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. -- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. -- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. +### Что реализовано и что перенесено + +Добавлены синхронная загрузка PNG/JPEG в приватный MinIO и авторизованное скачивание оригиналов. Метаданные хранятся в PostgreSQL; после остановки загрузившей API-реплики другой участник скачивает тот же файл через другую реплику с прежней сессией. + +- Из собственной HLAlab3 перенесены Go API, миграции, PostgreSQL, долговечные общие сессии Valkey, Argon2id, HAProxy с двумя API-репликами, keyset pagination и идемпотентная отправка сообщений. +- Сообщения поддерживают до 10 уникальных `attachment_ids` своего чата. Обычный текстовый POST остаётся валидным; отсутствие `attachment_ids` равнозначно `[]`. Параллельные повторы с одним ключом создают одно сообщение. +- Upload проверяет MIME по содержимому, целостность изображения, filename, лимиты 10 MiB и 40 млн пикселей. SHA-256 вычисляется при чтении; 201 ready возвращается после S3 PUT и COMMIT метаданных. Download возвращает исходные bytes через API без redirect. +- На API разрешены пять загрузок и одно декодирование одновременно; временные файлы ограничены tmpfs 64 MiB. Настроены таймауты, лимиты CPU/RAM, non-root/read-only API, `cap_drop=ALL` и `no-new-privileges`. +- Bootstrap bucket и отдельной ограниченной S3-учётной записи идемпотентен. MinIO backend изолирован в internal-сети; доступ проходит через закрытый listener HAProxy с фильтрами опасных запросов. Консоль и внутренние сервисы не публикуются на хосте. +- Реализован reconciler с read-only dry-run, применением исправлений и безопасным grace period. Под общей с upload блокировкой он повторно проверяет БД и S3 перед удалением старых orphan. Missing-метаданные и ссылки сообщений сохраняются; восстановленный оригинал проверяется по размеру и SHA-256. Сервис `cleanup` выполняет сверку периодически. + +Обязательный контракт, публичные тесты и README задания сохранены. Собственные проверки расположены в `student-tests/`. + +### Команды запуска из чистого clone + +Нужны Docker Desktop с Linux containers и Compose, Python 3.9+ и Go. Toolchain Go 1.27.3 закреплён в `go.mod`; версии образов и исходников MinIO/mc закреплены в Dockerfile/Compose. Команды выполняются из корня клона: + +```powershell +python -X utf8 scripts/bootstrap.py +python -X utf8 scripts/manage.py start +python -X utf8 scripts/verify.py +``` + +Bootstrap создаёт локальные `.env` и `secrets/`, сохраняя уже существующие значения. `start` собирает образы, выполняет миграции и S3 bootstrap, запускает стенд и ожидает готовности. Точка входа: `http://127.0.0.1:8080`. + +```powershell +# Состояние реальных контейнеров и хранилищ: +python -X utf8 scripts/manage.py status + +# Dry-run сверки, без изменения данных: +docker compose exec -T api /messenger reconcile + +# Остановка с сохранением данных: +docker compose down +``` + +Пошаговая ручная проверка регистрации, upload/download, SHA-256, ACL, persistence и failover: [MANUAL.md](../MANUAL.md). + +### Результаты проверок и отчёт + +Окончательный прогон завершён: **24/24 проверки успешны**, `complete=true`, `protected_unchanged=true` в [verification.json](../evidence/verification.json). + +- Пройдены структурная проверка, полная OpenAPI-валидация, Go unit-тесты, собственные тесты, `go vet` и `go test -race`. Проверки `make check` и `make test` выполнены эквивалентными командами Python; реальный вывод сохранён в `evidence/contract.txt` и `evidence/smoke.txt`. +- `govulncheck` приложения не выявил уязвимостей в вызываемом коде. Это не утверждение об отсутствии всех уязвимостей у стороннего MinIO. +- Публичные persistence и два failover-сценария сохранили подтверждённые данные, оригинал и прежние сессии. Время восстановления записи: **2,339 и 2,312 с**. +- Проверены повреждённые изображения, превышение bytes/pixels, подмена MIME, опасные имена, чужие вложения и привязка файла другого чата. Проверены private bucket, ограниченные S3-права, повторный bootstrap, отказ S3 и прерванное тело загрузки. +- Для PNG размером 207 687 и 7 466 790 bytes одновременно запущены по 10 запросов: **10/10 успешных загрузок в каждом профиле, 503 — 0**. Суммы индивидуальных kernel memory peaks двух API: **155,77 и 291,10 MiB**; это верхняя оценка общего пика, включая startup. +- В треке 2 воспроизведены ошибка БД после PUT и потеря объекта S3. Проверены dry-run без изменений, безопасный apply, повтор без новых изменений, защита fresh/used и восстановление по checksum. Стоимость обхода измерена тремя повторами для двух размеров набора объектов. + +Гипотеза, методика, измерения и ограничения: [REPORT.md](../REPORT.md). Сводка результатов: [RESULTS.md](../evidence/RESULTS.md). Raw summaries: [upload-memory.json](../evidence/upload-memory.json), [research.json](../evidence/research.json), [failures.json](../evidence/failures.json). + +- Исправлен сбой ожидания двух готовых API после пересоздания в memory-сценарии на Windows: собственные клиенты/verifier используют IPv4 loopback по умолчанию; явный `BASE_URL` сохранён. Добавлены пять регрессионных проверок, оба профиля 10/10 и полный прогон повторены. + +### Ограничения / известные ошибки + +- Один Docker-host, LB, PostgreSQL, Valkey и MinIO остаются точками отказа. Сохранение volumes не заменяет резервное копирование; reconciler не восстанавливает потерянные bytes без внешней копии. HTTP используется только на локальном стенде с синтетическими данными. +- MinIO Community архивирован. Применены сетевая изоляция и фильтрация unsigned-trailer uploads, служебных путей, S3 Select и replication headers. Область защиты и оставшиеся ограничения описаны в REPORT.md; production-безопасность всего стороннего сервера не заявляется. +- Для данного WSL2-host включён `GODEBUG=madvdontneed=0`: он уменьшил стоимость повторного выделения памяти без ослабления Argon2id, но может дольше удерживать RSS. Окончательный memory-эксперимент выполнен с этой настройкой. Измерения одного host не являются универсальными SLA или пределом производительности. + +### Источники и использование ИИ + +Использованы требования README/COURSE/contracts текущей лабораторной, собственная реализация HLAlab3, официальные исходники и документация MinIO/mc, MinIO Go SDK и Go runtime/image. ИИ использован для реализации, анализа требований и безопасности, подготовки тестов и документации. Заявленные результаты подтверждаются сохранёнными журналами и воспроизводимыми командами. + +- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. +- [x] Контракт и публичные тесты не ослаблены; неизменность проверена по SHA-256. +- [x] Проверки `make check` и `make test` выполнены эквивалентными командами Python; приложен реальный вывод. +- [x] Сценарии отказов/безопасности уровней 3 и 4 и выбранного трека 5 воспроизведены. +- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит токенов. +- [x] README задания сохранён, REPORT.md содержит инструкцию именно этого решения. diff --git a/.gitignore b/.gitignore index b5a71896..1aa95ec0 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,6 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. + +# Local diagnostic binaries +.diagnostics/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..5e2d25dc --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM golang:1.27.3-bookworm@sha256:d9b6a1beb9474adc2a1ce842573639b44b2a0dd49b6669f51d3821baf9ec37c9 AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY *.go ./ +COPY migrations ./migrations +RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /messenger . +FROM scratch AS runtime +COPY --from=build /messenger /messenger +USER 65532:65532 +ENV APP_HOST=0.0.0.0 APP_PORT=8080 GOMEMLIMIT=256MiB +EXPOSE 8080 +HEALTHCHECK --interval=5s --timeout=3s --start-period=10s --retries=3 CMD ["/messenger","healthcheck"] +STOPSIGNAL SIGTERM +ENTRYPOINT ["/messenger"] diff --git a/Dockerfile.minio b/Dockerfile.minio new file mode 100644 index 00000000..a8723b6b --- /dev/null +++ b/Dockerfile.minio @@ -0,0 +1,15 @@ +# Build official sources: upstream registry images are no longer public. +FROM golang:1.27.3-bookworm@sha256:d9b6a1beb9474adc2a1ce842573639b44b2a0dd49b6669f51d3821baf9ec37c9 AS build +ENV GOTOOLCHAIN=local CGO_ENABLED=0 +RUN go install -p 4 github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648 +RUN go install -p 4 github.com/minio/mc@v0.0.0-20250813083541-7394ce0dd2a8 +COPY infra/s3-health.go /health.go +RUN go build -trimpath -o /healthcheck /health.go +FROM alpine:3.23.3@sha256:25109184c71bdad752c8312a8623239686a9a2071e8825f20acb8f2198c3f659 AS tools +COPY --from=build /go/bin/mc /usr/bin/mc +ENTRYPOINT ["/usr/bin/mc"] +FROM scratch AS server +COPY --from=build /go/bin/minio /usr/bin/minio +COPY --from=build /healthcheck /healthcheck +COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt +ENTRYPOINT ["/usr/bin/minio"] diff --git a/Dockerfile.tests b/Dockerfile.tests new file mode 100644 index 00000000..a6206797 --- /dev/null +++ b/Dockerfile.tests @@ -0,0 +1,12 @@ +# Optional Linux tools for Windows hosts; contains no application secrets. +FROM docker:29.3.0-cli@sha256:067c301efe497cd5d174d468b7b3422a485ae4aca8f7ec1ffd4655c9fa383af2 AS cli +FROM golang:1.27.3-bookworm@sha256:d9b6a1beb9474adc2a1ce842573639b44b2a0dd49b6669f51d3821baf9ec37c9 +COPY --from=cli /usr/local/bin/docker /usr/local/bin/docker +COPY --from=cli /usr/local/libexec/docker/cli-plugins/docker-compose /usr/local/libexec/docker/cli-plugins/docker-compose +ENV PYTHONUTF8=1 PYTHONUNBUFFERED=1 GOTELEMETRY=off +RUN apt-get update && apt-get install -y --no-install-recommends python3 python3-venv make && rm -rf /var/lib/apt/lists/* +RUN python3 -m venv /opt/test-env +ENV PATH=/opt/test-env/bin:$PATH +COPY requirements-dev.txt /tmp/requirements-dev.txt +RUN pip install --no-cache-dir -r /tmp/requirements-dev.txt +WORKDIR /workspace diff --git a/MANUAL.md b/MANUAL.md new file mode 100644 index 00000000..99d299bc --- /dev/null +++ b/MANUAL.md @@ -0,0 +1,254 @@ +# Ручная проверка lab4 в PowerShell + +Все пользователи и файлы в этих командах синтетические. Нужны Docker Desktop с Linux containers, Python 3.9+ и Go 1.27.3. Команды выполняются из `C:\Users\maxsi\lab4\mtusi2026lab4-fork`. + +## 1. Запуск и полная проверка + +```powershell +cd C:\Users\maxsi\lab4\mtusi2026lab4-fork +python -X utf8 scripts/bootstrap.py +docker compose config --quiet +python -X utf8 scripts/manage.py start +python -X utf8 scripts/manage.py status +Invoke-RestMethod http://127.0.0.1:8080/health/ready + +# Полный последовательный прогон, включая отказы и эксперимент на «5»: +python -X utf8 scripts/verify.py +Get-Content evidence/verification.json +``` + +`complete: true` означает, что весь прогон закончен. `static_complete: true` при `complete: false` означает только локальные проверки исходников. При первом запуске сборка MinIO из официальных исходников может занять несколько минут. Bootstrap создаёт локальные `.env` и `secrets/`, повторный запуск сохраняет значения. + +## 2. Создать двух участников и постороннего + +```powershell +$base = 'http://127.0.0.1:8080' +function Send-LabJson($method, $path, $value, $headers = @{}) { + $bytes = [Text.Encoding]::UTF8.GetBytes(($value | ConvertTo-Json -Depth 6 -Compress)) + Invoke-RestMethod -Method $method -Uri ($base + $path) -Headers $headers ` + -ContentType 'application/json; charset=utf-8' -Body $bytes +} +function New-LabUser($label) { + $name = 'manual_' + $label + '_' + [guid]::NewGuid().ToString('N').Substring(0, 8) + $password = 'Lab-Test-' + [guid]::NewGuid().ToString('N') + $user = Send-LabJson POST '/api/v1/users' @{ + username = $name; display_name = $label; password = $password + } + $basic = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($name + ':' + $password)) + $session = Invoke-RestMethod -Method POST -Uri "$base/api/v1/auth/sessions" ` + -Headers @{Authorization = "Basic $basic"} + @{User = $user; Token = $session.token} +} +$alice = New-LabUser 'alice' +$bob = New-LabUser 'bob' +$eve = New-LabUser 'eve' +$ha = @{Authorization = 'Bearer ' + $alice.Token} +$hb = @{Authorization = 'Bearer ' + $bob.Token} +$he = @{Authorization = 'Bearer ' + $eve.Token} +$chat = Send-LabJson POST '/api/v1/chats' @{ + title = 'Проверка вложений'; member_ids = @($alice.User.id, $bob.User.id) +} $ha +$chat.id +``` + +Не выводите переменные с токенами, паролями или Basic-заголовками и не добавляйте их в отчёт. + +## 3. Загрузить, отправить и скачать оригинал + +```powershell +$fixture = Join-Path (Get-Location) 'tests/fixtures/sample.png' +$upload = Invoke-WebRequest -UseBasicParsing -Method POST ` + -Uri "$base/api/v1/chats/$($chat.id)/attachments?filename=photo.png" ` + -Headers $ha -ContentType 'image/png' -InFile $fixture +$upload.StatusCode # 201 +$uploader = $upload.Headers['X-Instance-Id'] +$att = $upload.Content | ConvertFrom-Json +$att | Select-Object id, status, content_type, size_bytes, sha256 + +$key = [guid]::NewGuid().ToString('N') +$hm = @{Authorization = $ha.Authorization; 'Idempotency-Key' = $key} +$message = Send-LabJson POST "/api/v1/chats/$($chat.id)/messages" @{ + text = ''; attachment_ids = @($att.id) +} $hm +$repeat = Send-LabJson POST "/api/v1/chats/$($chat.id)/messages" @{ + attachment_ids = @($att.id); text = '' +} $hm +$message.id -eq $repeat.id # True: ровно одно сообщение + +Invoke-WebRequest -UseBasicParsing -Uri "$base/api/v1/attachments/$($att.id)/content" ` + -Headers $hb -OutFile 'evidence/manual-download.png' +$expected = (Get-FileHash $fixture -Algorithm SHA256).Hash.ToLowerInvariant() +$actual = (Get-FileHash 'evidence/manual-download.png' -Algorithm SHA256).Hash.ToLowerInvariant() +($actual -eq $expected) -and ($actual -eq $att.sha256) # True +Invoke-RestMethod "$base/api/v1/chats/$($chat.id)/messages" -Headers $hb +``` + +`status=ready`, `variants=[]`, `error_code=null`; в истории есть `attachment_ids`. Обычный POST `{"text":"Привет"}` с новым Idempotency-Key по-прежнему работает и возвращает `attachment_ids=[]`. Повтор того же ключа с другим текстом даёт 409. + +## 4. Доступ и ошибки файла + +```powershell +try { + Invoke-WebRequest -UseBasicParsing "$base/api/v1/attachments/$($att.id)" -Headers $he +} catch { [int]$_.Exception.Response.StatusCode } # 404 +try { + Invoke-WebRequest -UseBasicParsing "$base/api/v1/attachments/$($att.id)/content" -Headers $he +} catch { [int]$_.Exception.Response.StatusCode } # 404 +try { + Invoke-WebRequest -UseBasicParsing -Method POST ` + -Uri "$base/api/v1/chats/$($chat.id)/attachments?filename=..%2Fphoto.png" ` + -Headers $ha -ContentType 'image/png' -InFile $fixture +} catch { [int]$_.Exception.Response.StatusCode } # 400 +try { + Invoke-WebRequest -UseBasicParsing -Method POST ` + -Uri "$base/api/v1/chats/$($chat.id)/attachments?filename=photo.jpg" ` + -Headers $ha -ContentType 'image/jpeg' -InFile $fixture +} catch { [int]$_.Exception.Response.StatusCode } # 415 + +# Также: >10 MiB -> 413, >40 млн пикселей -> 413, +# повреждённый PNG/JPEG -> 415, файл другого чата -> 404: +python -X utf8 student-tests/attachments.py +``` + +## 5. Остановить именно загрузившую API-реплику + +```powershell +python -X utf8 scripts/manage.py stop-one --instance $uploader +Start-Sleep -Seconds 2 +$other = Invoke-WebRequest -UseBasicParsing ` + -Uri "$base/api/v1/attachments/$($att.id)/content" -Headers $hb ` + -OutFile 'evidence/manual-after-failover.png' -PassThru +$other.Headers['X-Instance-Id'] -ne $uploader # True +(Get-FileHash 'evidence/manual-after-failover.png').Hash -eq (Get-FileHash $fixture).Hash # True +python -X utf8 scripts/manage.py restore +``` + +Другая реальная реплика должна вернуть те же байты с прежним токеном. Сопоставление `X-Instance-Id` с контейнерами видно в `scripts/manage.py status`. + +## 6. Перезапуск, недоступность S3 и приватность + +```powershell +python -X utf8 scripts/manage.py restart +# Сохраняются прежние $hb и $att, повторный вход не нужен: +Invoke-RestMethod "$base/api/v1/attachments/$($att.id)" -Headers $hb +Invoke-WebRequest -UseBasicParsing "$base/api/v1/attachments/$($att.id)/content" ` + -Headers $hb -OutFile 'evidence/manual-after-restart.png' +(Get-FileHash 'evidence/manual-after-restart.png').Hash -eq (Get-FileHash $fixture).Hash # True + +# Приватность, отдельные S3-права, два bootstrap, отказ S3, +# оборванное тело и остановка именно uploader проверяются здесь: +python -X utf8 student-tests/failures.py +Get-Content evidence/failures.json + +# Публичные persistence/failover с неизменёнными tests/: +docker build -f Dockerfile.tests -t mtusi-messenger:lab4-tests . +python -X utf8 scripts/linux_tests.py test-persistence +python -X utf8 scripts/linux_tests.py test-failover +python -X utf8 scripts/manage.py restore +``` + +При полном отказе S3 API `/health/live` остаётся 200, readiness/upload/download возвращают 503. LB после исключения всех backend может вернуть собственный 503 без JSON; `failures.py` отдельно проверяет JSON-ошибку непосредственно на внутреннем API без публикации его порта. MinIO API/консоль, PostgreSQL, Valkey и реплики не публикуются на хосте; наружу открыт только LB на `127.0.0.1:8080`. Анонимный запрос в S3 из внутренней сети должен получить 403. + +Для проверки сохранности используйте `docker compose down` и затем `up`, сохраняя volumes. Команда с удалением volumes для этого сценария не подходит. + +## 7. Исследование на «5» и память на «4» + +```powershell +# По умолчанию только чтение, grace = 3600 секунд: +docker compose exec -T api /messenger reconcile +# Безопасно применить исправления после анализа dry-run: +docker compose exec -T api /messenger reconcile --apply +# Повтор должен показать deleted=0 при отсутствии новых старых orphan: +docker compose exec -T api /messenger reconcile --apply + +# Контролируемая инъекция ошибок, реальное ожидание grace >=60 секунд, +# dry-run/apply/repeat, восстановление SHA-256, защита fresh/used, +# три измерения обхода при двух размерах набора: +python -X utf8 student-tests/research.py +Get-Content evidence/research.json + +# 10 одновременно стартующих клиентов, два размера PNG, +# успешные запросы и 503 от ограничения параллелизма учитываются отдельно: +python -X utf8 student-tests/memory.py +Get-Content evidence/upload-memory.json +``` + +Незаписанный объект удаляется только старше grace, после повторной проверки БД под той же блокировкой, которую использует upload. Существующие метаданные защищают объект независимо от наличия сообщения. При потере оригинала сохраняются и метаданные, и ссылки сообщений; API отвечает 503. После восстановления точных байтов reconciler проверяет SHA-256 и снимает отметку недоступности. + +`research.py` оставляет свежие синтетические orphan для проверки grace; обычный reconciler сможет убрать их после истечения срока. Сервис `cleanup` автоматически выполняет `reconcile --apply` каждые 15 минут с grace 3600 секунд. Ручной CLI позволяет сначала изучить dry-run. Два параллельных обхода безопасны благодаря блокировкам и повторным проверкам. + +## 8. Что добавлять в Git + +Добавляйте реализацию, миграции, Compose/Dockerfile, `infra/`, собственные `student-tests/`, операторские скрипты, `MANUAL.md`, `REPORT.md` и небольшие проверенные `evidence/*.json`/`*.txt`. Перед коммитом проверьте `git diff --cached`. Не добавляйте `.env`, `secrets/`, `.venv/`, токены, временные файлы и большие логи сборки. `contracts/` и публичные `tests/` должны остаться без изменений. + + +MinIO дополнительно изолирован в сети `object_store`. Имя `s3` в общей сети ведёт на закрытый S3-listener HAProxy; исходный backend туда не подключён. Фильтр блокирует unsigned-trailer uploads и неиспользуемые служебные функции архивированного MinIO. Проверки фильтра входят в `student-tests/failures.py`; область и ограничения защиты описаны в REPORT.md. + +Если завершились локальные/race проверки, а исправлена только инфраструктура или её проверка, можно продолжить `python -X utf8 scripts/verify.py --resume-integration`. Verifier проверяет неизменность исходников приложения и заново выполняет все интеграционные сценарии. При изменении Go-кода нужен полный запуск без этого флага. + + +## 9. Показать private bucket без API + +Выполняется после шага 3, в том же PowerShell. Тестовый Linux-образ собирается в шаге 6 или полным verifier. URL доступен только внутри сети стенда; используется тот же UUID загруженного файла. + +```powershell +$s3Url = "http://s3:9000/messenger-attachments/original/$($att.id)" +$anonymousProbe = @' +import sys, urllib.request, urllib.error +try: + response = urllib.request.urlopen(sys.argv[1], timeout=5) + print(response.status) +except urllib.error.HTTPError as error: + print(error.code) +'@ +docker run --rm --network mtusi-lab4_default mtusi-messenger:lab4-tests ` + python -c $anonymousProbe $s3Url +# Ожидается 403; тот же файл через API участника скачивается с 200. +``` + +## 10. Повторить диагностику возврата памяти (необязательно) + +Используются только синтетические данные. Argon2id остаётся 64 MiB/t=3/p=1; после каждого хеша вызывается FreeOSMemory для воспроизводимого холодного выделения страниц. Диагностические контейнеры не подключаются к сети и не получают секреты/volumes стенда. + +```powershell +New-Item -ItemType Directory -Force .diagnostics | Out-Null +Copy-Item student-tests/kdf-bench.go.txt .diagnostics/kdfbench.go +$labOldGoOS = $env:GOOS +$labOldCgo = $env:CGO_ENABLED +try { + $env:GOOS = 'linux' + $env:CGO_ENABLED = '0' + go build -trimpath -o .diagnostics/kdfbench .diagnostics/kdfbench.go +} finally { + $env:GOOS = $labOldGoOS + $env:CGO_ENABLED = $labOldCgo +} +$benchPath = (Resolve-Path .diagnostics/kdfbench).Path +docker run --rm --network none --cpus 1 --memory 768m --read-only ` + --cap-drop ALL --security-opt no-new-privileges:true --no-healthcheck ` + -e GOMEMLIMIT=512MiB --mount "type=bind,source=$benchPath,target=/bench,readonly" ` + --entrypoint /bench mtusi-messenger:lab4 +docker run --rm --network none --cpus 1 --memory 768m --read-only ` + --cap-drop ALL --security-opt no-new-privileges:true --no-healthcheck ` + -e GOMEMLIMIT=512MiB -e GODEBUG=madvdontneed=0 ` + --mount "type=bind,source=$benchPath,target=/bench,readonly" ` + --entrypoint /bench mtusi-messenger:lab4 +``` + +Режим MADV_FREE уже включён в Compose для API. Он может дольше удерживать RSS; итоговый memory-эксперимент проверен именно с этой настройкой. Полный прогон завершён успешно, обе серии из десяти uploads дали 10/10. + + +## 11. Если memory останавливается на readiness + +На Windows `localhost` может отвечать заметно медленнее IPv4 loopback. В воспроизведённом сбое обе API были healthy и OOMKilled=false; ошибка возникала до загрузок, при ожидании двух различных `X-Instance-Id`. Собственные клиенты и полный verifier теперь по умолчанию используют `127.0.0.1`, сохраняя явно заданный `BASE_URL`. Публичные тесты не изменены. + +```powershell +$env:BASE_URL = 'http://127.0.0.1:8080' +python -X utf8 student-tests/readiness_test.py +python -X utf8 student-tests/memory.py +Get-Content evidence/upload-memory.json +# Полная проверка в исходной последовательности: +python -X utf8 scripts/verify.py +``` + +Ожидается `PASS 10-client memory experiment at two sizes`, два профиля с `success=10`, `backpressure_503=0`, `complete=true`. Исходный traceback сохранён в `evidence/memory-before-ipv4-fix.txt`. При новой ошибке смотрите текущий `evidence/memory.txt`: сводка upload-memory.json сохраняется только после успешного завершения обоих профилей и сама по себе не доказывает успех более позднего запуска. diff --git a/REPORT.md b/REPORT.md index 9ad2b84f..baab0581 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,452 @@ # Отчёт — лабораторная 4 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- **Автор, группа:** Ситосенко, БВТ2303. +- **Целевая оценка; выбранный трек 5:** 5; трек 2 — согласованность PostgreSQL и S3. Выполнены накопительные требования уровней 3 и 4. +- **Commit/PR:** рабочая ветка `solution/bvt2303-sitosenko`. [PR №N39](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/39). +- **Использованные источники, библиотеки и помощь ИИ:** требования README/COURSE/contracts текущего репозитория, собственная HLAlab3; Go, pgx, go-redis, Argon2id и MinIO Go SDK. Официальные материалы перечислены в дополнительном разделе. ИИ использован при реализации, анализе требований и безопасности, подготовке тестов и документации. Числа результатов взяты из сохранённых evidence. + +**Статус:** окончательный прогон завершён 30.10.2026 20:39:24 МСК; все 24 проверки успешны, `complete=true`, `protected_unchanged=true`. Контракт и публичные тесты сохранены. Сводка: [RESULTS.md](evidence/RESULTS.md); машинный журнал: [verification.json](evidence/verification.json). ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +### Предварительные условия и версии + +Нужны Docker Desktop с Linux containers и Compose, Python 3.9+ и установленный Go. В `go.mod` закреплён toolchain Go 1.27.3, который Go загрузит при необходимости. В зафиксированном прогоне на Windows использовался Python 3.14.0. HTTP-проверки используют стандартную библиотеку Python. Полная OpenAPI-валидация и race-проверка выполняются в Linux test-образе. + +| Компонент | Закреплённая версия / источник | Где закреплено | +| --- | --- | --- | +| Go builder | 1.27.3-bookworm и SHA-256 digest | `Dockerfile`, `Dockerfile.minio`, `Dockerfile.tests` | +| PostgreSQL | 17.6-bookworm и digest | `compose.yaml` | +| Valkey | 8.1.3-bookworm и digest | `compose.yaml` | +| HAProxy | 3.2.6-alpine | `compose.yaml` | +| MinIO | RELEASE.2025-10-15T17-29-55Z; исходники `v0.0.0-20251015172955-9e49d5e7a648` | `Dockerfile.minio` | +| MinIO Client mc | RELEASE.2025-08-13T08-35-41Z; исходники `v0.0.0-20250813083541-7394ce0dd2a8` | `Dockerfile.minio` | +| Основа mc tools | Alpine 3.23.3 и digest | `Dockerfile.minio` | +| Docker CLI тестового образа | 29.3.0-cli и digest | `Dockerfile.tests` | +| OpenAPI validator | openapi-spec-validator 0.7.2 | `requirements-dev.txt` | + +MinIO и mc собираются из официальных исходников с фиксированными Go pseudo-versions; зависимости проверяются Go checksum database. Образы с тегом `latest` не используются. Сборка MinIO при первом запуске может занять несколько минут. + +### Создание локальных настроек, сборка и запуск + +Команды ниже выполняются из корня клона в PowerShell. Локальные PostgreSQL/Valkey/MinIO вне Compose не нужны. + +```powershell +python -X utf8 scripts/bootstrap.py +docker compose --env-file .env config --quiet +python -X utf8 scripts/manage.py start +python -X utf8 scripts/manage.py status +Invoke-RestMethod http://127.0.0.1:8080/health/ready +``` + +`bootstrap.py` создаёт `.env` и случайные секреты в `secrets/`, не печатает значения и не заменяет существующие. Эти файлы исключены из Git и Docker build context. Их содержимое не требуется вставлять в команды или отчёт. + +`manage.py start` повторно безопасно вызывает bootstrap, затем выполняет `docker compose up -d --build --wait` и ожидает две разные готовые API-реплики через LB. Одноразовый `migrate` применяет миграции под общей блокировкой и сверяет checksum уже применённых файлов. `s3-init` создаёт приватный bucket и ограниченную учётную запись, после чего запускаются API и cleanup. Нормальный результат readiness — `200 {"status":"ok"}`; завершённые `migrate` и `s3-init` имеют exit code 0. + +### Проверки после запуска + +```powershell +# Полный последовательный прогон: исходники, схема, HTTP, отказы и эксперименты. +python -X utf8 scripts/verify.py +Get-Content evidence/verification.json + +# Публичный минимум отдельно; эквиваленты целей make check и make test. +python -X utf8 scripts/check_contract.py +python -X utf8 tests/smoke.py --base-url http://127.0.0.1:8080 + +# Неизменённые публичные persistence/failover с Linux hooks. +docker build -f Dockerfile.tests -t mtusi-messenger:lab4-tests . +python -X utf8 scripts/linux_tests.py test-persistence +python -X utf8 scripts/linux_tests.py test-failover +python -X utf8 scripts/manage.py restore +``` + +После полного прогона ожидается `complete=true`, каждый `exit_code` равен 0. Локальные/race результаты последнего полного запуска переиспользованы только для неизменённого Go-кода; после изменения runtime-конфигурации вся интеграционная часть выполнена заново. `--resume-integration` проверяет, что исходники приложения не стали новее соответствующего запуска. Сам по себе структурный `check` не проверяет работоспособность сервера. + +Подробные запросы регистрации, загрузки, отправки сообщения с файлом, скачивания, SHA-256 и доступа постороннего приведены в [MANUAL.md](MANUAL.md). + +### Безопасная остановка и намеренный сброс данных + +```powershell +# Остановить стенд и сохранить данные и сессии: +docker compose down + +# Повторный запуск использует прежние volumes и секреты: +python -X utf8 scripts/manage.py start +``` + +Отдельная команда для намеренного полного удаления **учебных** данных этого Compose-проекта: + +```powershell +# Удалит named volumes pgdata, sessions и objects вместе с данными. +# Для persistence/failover эту команду не применять. +docker compose down --volumes +``` + +Удаление volumes уничтожает пользователей, сообщения, сессии и оригиналы; после такого сброса проверять сохранность прежних данных нельзя. Скрипты `restart`, `restore` и публичные hooks volumes не удаляют. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +### Процессы, сеть и источник истины + +```text +Клиент -> 127.0.0.1:8080 -> HAProxy:8080 -> API x2 -> PostgreSQL + | -> Valkey + | -> HAProxy:9000 -> MinIO + тот же lb private backend + +migrate -> PostgreSQL s3-init -> private S3 listener +cleanup -> PostgreSQL + private S3 listener +``` + +PostgreSQL — источник истины пользователей, чатов, членства, сообщений и метаданных Attachment. Valkey хранит общие серверные сессии с expiry. MinIO хранит bytes оригиналов в приватном bucket `messenger-attachments`. Named volumes: `pgdata`, `sessions`, `objects` соответственно. + +Только `lb` публикует `127.0.0.1:8080`. API, PostgreSQL и Valkey не имеют опубликованных портов. MinIO подключён только к internal-сети `object_store`, где находятся MinIO и HAProxy. В общей сети alias `s3` ведёт на закрытый S3-listener того же HAProxy на порту 9000; raw backend доступен HAProxy как `minio-backend`. Порт 9000 на хост не публикуется. Консоль MinIO отключена и привязана к loopback контейнера. + +| Сервис | Назначение | Постоянные данные / жизненный цикл | +| --- | --- | --- | +| `db` | Метаданные и транзакции PostgreSQL | `pgdata` | +| `valkey` | Общие сессии | `sessions`, AOF с `appendfsync always` | +| `s3` | MinIO backend | `objects` | +| `lb` | Публичный API listener и закрытый S3 listener | Состояние приложения не хранит | +| `api` ×2 | REST, ACL, upload/download, сообщения | Постоянного локального состояния нет | +| `migrate` | Миграции с checksum и блокировкой | Одноразовый, exit 0 после успеха | +| `s3-init` | Bucket, private policy, ограниченный S3-пользователь | Одноразовый, повторный запуск безопасен | +| `cleanup` | Периодический reconciler | Истина остаётся в БД/S3; результат — агрегированный журнал | + +HAProxy использует round-robin, Docker DNS и readiness checks каждые 500 мс с `fall 2`/`rise 2`. Sticky sessions не используются. Сессия читается любой репликой из Valkey, а подтверждённое сообщение — из общей PostgreSQL. + +### Что перенесено из HLAlab3 и что добавлено + +Сохранены Go REST API, миграции, Argon2id, Bearer-сессии, общая долговечная Valkey, keyset pagination, `X-Request-Id`, стабильный `X-Instance-Id`, HAProxy и идемпотентная запись сообщений. Обязательный контракт lab4 и публичные проверки взяты из текущей лабораторной; `.git`, секреты и публичный контракт предыдущей лабы поверх них не переносились. + +Добавлены `attachments.go`, `reconcile.go`, локальная cgroup-диагностика, миграция `004_attachments.sql`, MinIO/mc build, bootstrap/IAM policy, S3-фильтры, cleanup и собственные тесты. `attachments` связывает оригинал с чатом и владельцем, содержит server-generated object key, filename, content type, size, SHA-256, timestamps и внутренний `missing_since`. Сообщение хранит `attachment_ids`; таблица `message_attachments` сохраняет ссылки с внешними ключами. + +В публичном Attachment не возвращаются S3 object key, credentials и внутренние адреса. Для lab4 статус синхронный: `ready`, `variants=[]`, `error_code=null`. Асинхронные 202/worker/thumbnail относятся к следующей лабораторной и здесь не добавляются. + +### Границы upload/download и идемпотентности + +1. Сначала проверяются сессия и доступ к чату. Filename — только отображение: 1–255 code points, без `/`, `\`, NUL и управляющих символов. +2. Raw body потоком копируется во временный файл, одновременно считается SHA-256. Content-Length и `MaxBytesReader` ограничивают тело 10 MiB, включая chunked. +3. `DecodeConfig` проверяет фактический PNG/JPEG и ≤40 млн пикселей до полного декодирования; полный `Decode` отклоняет повреждённое изображение. Content-Type обязан соответствовать содержимому. +4. Под транзакционной блокировкой `attachment:` выполняются S3 PUT, INSERT метаданных и COMMIT. Только после успеха возвращается 201 ready. Ключ формируется сервером как `original/`. +5. Временный файл закрывается и удаляется после запроса. Это ограниченный staging в tmpfs, не постоянный оригинал API. Download читает объект из MinIO потоком после ACL, без redirect, с истинным Content-Type, `Content-Disposition: attachment`, `nosniff` и `private, no-store`. + +Любой участник чата может читать и прикреплять его вложение. Неизвестный/чужой ID и вложение другого чата дают 404. Пустой или пробельный text разрешён только с вложениями; максимум 10 уникальных UUID. Обычный текстовый POST остаётся валидным, пропущенный `attachment_ids` равнозначен `[]`. + +Идемпотентность сообщения имеет scope пользователь + чат + ключ; POST и путь неявно заданы таблицей этого endpoint. Общая advisory lock сериализует повторы через разные API. Message, связи вложений и запись результата фиксируются одной транзакцией. Тот же валидный текст и массив ID возвращают исходный Message/201, другой body — 409. Срок хранения результата не меньше 24 часов. Неопределённый upload POST прозрачно не повторяется: он не имеет обязательной идемпотентности. + +### Согласованность двух хранилищ + +Распределённой транзакции PostgreSQL + S3 нет. Если PUT прошёл, а INSERT/COMMIT — нет, возможен orphan: объект без метаданных. При неопределённом COMMIT немедленный DELETE опасен, поскольку фиксация могла состояться. Поэтому решение сохраняет объект до безопасной сверки. + +Reconciler по умолчанию работает в dry-run. Для применения нужен `--apply`. Grace — 3600 секунд, минимально 60; cutoff берётся из PostgreSQL. Для управляемого ключа `original/` после LIST под той же блокировкой заново проверяется отсутствие строки и актуальный HEAD LastModified. Любая существующая строка защищает объект независимо от наличия сообщения. Fresh и занятые ключи пропускаются; незнакомые ключи не удаляются. + +Missing означает обратную ситуацию: строка есть, объект отсутствует. Для старого missing устанавливается внутренний `missing_since`, но метаданные и ссылки сообщений не удаляются. Участник получает 503, посторонний — по-прежнему 404. После восстановления объекта проверяются полный размер и SHA-256, затем отметка снимается. Timeout, 403, NoSuchBucket и 5xx не считаются отсутствием объекта: обход прерывается с `complete=false`. + +Обычный metadata-pass проверяет наличие и размер; полное чтение с SHA-256 выполняется при восстановлении missing. Это сверка orphan/missing, а не полный побайтовый аудит каждого ready-оригинала. Строки БД обходятся keyset-страницами по 256 ID. Обычная стоимость — O(N объектов + M строк); восстановление дополнительно читает bytes нужного оригинала. + +`cleanup` запускает apply при старте и через 15 минут после завершения предыдущего обхода; один обход ограничен 10 минутами. Manual CLI и cleanup используют одинаковые проверки и блокировки. + +### Лимиты, таймауты и секреты + +| Ограничение | Окончательная настройка | +| --- | --- | +| Тело оригинала | ≤10 485 760 bytes | +| Декодируемая размерность | ≤40 000 000 пикселей | +| Загрузки / полные декодирования | 5 / 1 на API-процесс | +| Временный staging | tmpfs 64 MiB, noexec/nosuid/nodev; ≤50 MiB исходников по admission | +| Общие in-flight запросы | 32 на API | +| KDF | 2 одновременно; Argon2id 64 MiB/t=3/p=1 | +| API RAM / Go soft limit | 768 MiB / GOMEMLIMIT 512 MiB | +| HTTP read и context / write | 30 / 35 с | +| LB client/server | 40 с | +| S3 connect / response headers | 2 / 5 с; один SDK attempt | +| PostgreSQL statement / lock timeout | 3 / 1 с для API | + +Лимиты bytes/pixels проверяются до неограниченного чтения/распаковки. Полное декодирование синхронно и само не принимает context: внешние операции используют deadline, а для декодирования ограничителями остаются bytes, pixels, семафор и cgroup. GOMEMLIMIT — мягкий предел Go heap, не гарантия RSS; рабочие строки декодера также требуют памяти. + +API запущены с UID/GID 65532, read-only rootfs, `cap_drop=ALL`, `no-new-privileges`, pids limit 128. В Compose для API включён `GODEBUG=madvdontneed=0`; измерения RAM ниже относятся именно к нему. Ограничение хеширования не ослаблялось. Проверенные настройки и отсутствие OOMKilled у финальных реплик сохранены в [security-extra.json](evidence/security-extra.json). + +API/cleanup получают только отдельные S3 credentials: GetBucketLocation/ListBucket одного bucket, GetObject/PutObject/DeleteObject только `original/*`. Root-секреты смонтированы только в MinIO/bootstrap. Нет прав API на управление пользователями, создание bucket и запись вне prefix. Пароли, токены и значения ключей в отчёт не включены. PostgreSQL зафиксирован с `fsync=on`, `synchronous_commit=on`, `full_page_writes=on`. + +### Соответствие .env.example реальной конфигурации + +| Настройка skeleton | Отображение в решении | +| --- | --- | +| APP_HOST / APP_PORT / APP_ENV | API слушает 0.0.0.0:8080 внутри контейнера; APP_PORT задаёт loopback-порт LB; APP_ENV передаётся API | +| SESSION_STORE | Bootstrap нового `.env` заменяет предложенный `postgres` на `valkey`; реализация использует Valkey | +| SESSION_TTL_SECONDS | По умолчанию 3600, абсолютный expiry не продлевается рестартом | +| DATABASE_URL_FILE / CACHE_URL_FILE | Файлы Compose secrets, адреса db/valkey внутри стенда | +| API_REPLICAS | По умолчанию 2; HAProxy server-template рассчитан на 1–4 backend | +| IDEMPOTENCY_TTL_SECONDS | По умолчанию 86400; код запрещает значение меньше суток | +| S3_ENDPOINT / REGION / BUCKET | Compose задаёт http://s3:9000 / us-east-1 / messenger-attachments; s3 — alias закрытого proxy в общей сети | +| S3_ACCESS_KEY_ID_FILE / SECRET_ACCESS_KEY_FILE | Отдельные файлы ограниченной учётной записи; значения не лежат в environment/образе | +| MAX_UPLOAD_BYTES / MAX_IMAGE_PIXELS | Контрактные максимумы фиксированы в коде; переменные из worksheet не позволяют повысить их | +| Дополнения решения | CURSOR_SECRET_FILE, DB_POOL_MAX=8, MAX_INFLIGHT=32, GOMEMLIMIT=512MiB и GODEBUG | + +Readiness зависит от PostgreSQL, Valkey и доступности bucket через ограниченные S3 credentials; liveness проверяет процесс. При отказе S3 API возвращает JSON 503. Когда LB исключил все backend, он может вернуть собственный транспортный 503; формат ошибки приложения отдельно проверяется непосредственно во внутренней сети. ## Доказательства критериев +Каждая строка ниже связывает требование с командой, наблюдением и сохранённым файлом. Цели `make check`/`make test` и прямые Python-команды запускают те же публичные проверки. Контракт и assertions не ослаблялись. + | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +| Целостность skeleton и публичных файлов | `python -X utf8 scripts/check_contract.py`; SHA-256 manifest | PASS; неизменны 12 файлов contracts/tests | [contract.txt](evidence/contract.txt), [protected-files.json](evidence/protected-files.json) | +| Полная OpenAPI 3.1 / JSON Schema | `python -X utf8 scripts/linux_tests.py validate` | PASS; схема и примеры валидны | [openapi.txt](evidence/openapi.txt) | +| Публичный smoke | `python -X utf8 tests/smoke.py` | PASS lab4: пользователи, чат, сообщения, pagination, файл, ACL, logout | [smoke.txt](evidence/smoke.txt) | +| 3: сохранён обязательный минимум lab3 | Публичный smoke + concurrent replay в own tests | Прежние текстовые POST, Bearer, Idempotency-Key, единый результат повтора | [attachments.json](evidence/attachments.json), [failover-1.txt](evidence/failover-1.txt) | +| 3: PostgreSQL metadata и приватный S3 для bytes | Compose, миграция 004, infrastructure snapshot | 2 API; metadata в БД, original в MinIO, локального persistent state API нет | [infrastructure.json](evidence/infrastructure.json), [security-extra.json](evidence/security-extra.json) | +| 3: 201 ready и побайтный оригинал | Upload → message с attachment_ids → GET content другим участником | SHA-256/size совпадают; PNG и JPEG не перекодированы | [smoke.txt](evidence/smoke.txt), [attachments.json](evidence/attachments.json) | +| 3: MIME, bytes/pixels и filename | `python -X utf8 student-tests/attachments.py`; own unit | Подмена/повреждение 415, превышение 413, опасное имя 400 | [attachments.json](evidence/attachments.json), [student-unit.txt](evidence/student-unit.txt) | +| 3: остановка именно uploader | `python -X utf8 student-tests/failures.py` | Header сопоставлен с реальным контейнером; другая API вернула те же bytes с прежней сессией | [failures.json](evidence/failures.json) | +| 3: restart всех хранилищ и API | `python -X utf8 scripts/linux_tests.py test-persistence` | Данные, исходный файл и старый токен сохранились; volumes не удалялись | [persistence.txt](evidence/persistence.txt), [restart-before.txt](evidence/restart-before.txt), [restart-after.txt](evidence/restart-after.txt) | +| 4: отрицательные file/ACL кейсы | Повреждение, MIME spoof, чужой ID, attachment другого чата | Ожидаемые 400/404/413/415; пользовательские ошибки не дают 500 | [attachments.json](evidence/attachments.json) | +| 4: прерванное тело | Закрыть соединение до Content-Length | Новых metadata не появилось; обработчик восстановился | [failures.json](evidence/failures.json) | +| 4: отказ после PUT и безопасная очистка | SQL trigger для одного синтетического filename; real grace 65 с | Обнаружен orphan; старые неучтённые объекты очищены, fresh/used сохранены | [research.json](evidence/research.json) | +| 4: ≥10 одновременных uploads и peak RAM | `python -X utf8 student-tests/memory.py` | Оба размера: 10/10, ошибок 0; kernel peaks и CPU samples записаны | [upload-memory.json](evidence/upload-memory.json) | +| 4: private bucket и least privilege | Anonymous GET вне API; административные и outside-prefix операции API credentials | 403 на anonymous GET; запрещены admin/create-bucket/outside-prefix | [failures.json](evidence/failures.json) | +| 4: bootstrap повторяем, console закрыта | Два повторных s3-init; inspect/network probe | Оригинал сохранился; MinIO console/порты не опубликованы; raw backend из сети приложения недоступен | [failures.json](evidence/failures.json), [security-extra.json](evidence/security-extra.json) | +| 5: две стороны отказа | Ошибка PostgreSQL после PUT; удаление bytes подтверждённого Attachment | Обнаружены orphan и missing; metadata и ссылки missing не удалены | [research.json](evidence/research.json) | +| 5: dry-run/apply/повтор | Последовательные режимы CLI | Dry-run: 0 изменений; apply: безопасная очистка; повтор: deleted=0, новых отметок 0 | [research.json](evidence/research.json) | +| 5: защита fresh и используемых | Fresh orphan + прикреплённый original + параллельные uploads | Fresh и used сохранились; подтверждённые uploads читаются побайтно | [research.json](evidence/research.json) | +| 5: восстановление missing | Восстановить fixture → reconcile --apply | Размер/SHA-256 проверены, одна отметка снята, bytes доступны | [research.json](evidence/research.json) | +| 5: стоимость обхода | По три dry-run для 144 и 244 объектов | 133 metadata rows; время и количество HEAD записаны для каждого повтора | [research.json](evidence/research.json) | +| Дополнительно: Go correctness / race | `go test ./...`; own unit; `go vet ./...`; `go test -race ./...` | Все exit code 0 | [verification.json](evidence/verification.json), [student-unit.txt](evidence/student-unit.txt), [go-race.txt](evidence/go-race.txt) | +| Дополнительно: уязвимости приложения | `go run golang.org/x/vuln/cmd/govulncheck@v1.1.4 ./...` | 0 уязвимостей в вызываемом коде; 3 module-level записи без соответствующих вызовов | [go-vuln.txt](evidence/go-vuln.txt) | -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +### Подтверждение реального restart/stop hook + +Persistence hook перезапускает `db valkey s3 api lb`. Для каждого контейнера ниже ID до/после одинаков, а StartedAt изменился. Это подтверждает restart реальных процессов, включая PostgreSQL, Valkey и MinIO. Времена показаны по Москве; raw evidence хранит UTC. + +| Роль / короткий container ID | StartedAt до, МСК | StartedAt после, МСК | +| --- | --- | --- | +| api / `287d13f6fa5a` | 20:33:31.254 | 20:34:47.995 | +| api / `23cdf8687348` | 20:33:30.967 | 20:34:47.782 | +| db / `c6b006c443fa` | 20:20:40.094 | 20:34:46.279 | +| lb / `61d73bbbe539` | 20:20:40.921 | 20:34:56.637 | +| s3 / `72035d94e70a` | 20:22:13.846 | 20:34:46.171 | +| valkey / `96dc99b9811c` | 20:20:40.048 | 20:34:46.422 | + +Последний public stop-one hook сохранил тот же container ID со сменой `running` → `exited`, exit code 0: [stopped-before.txt](evidence/stopped-before.txt) и [stopped-after.txt](evidence/stopped-after.txt). Hook выбирает контейнер по `TARGET_INSTANCE_ID`, а не останавливает произвольную реплику. Отдельный own test сопоставляет header именно upload-ответа с uploader-контейнером. ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +### Среда, ресурсы и объём данных + +Снимок среды: [infrastructure.json](evidence/infrastructure.json). Docker Engine 29.3.0, Linux kernel `6.18.54.1-microsoft-standard-WSL2`, Docker Desktop/WSL2. Docker VM видит 12 CPU и 3.68 GiB RAM (3956068352 bytes). Это доступные VM ресурсы, не модель физического CPU или объём RAM Windows-host; последние отдельно не фиксировались. + +| Компонент | Количество | CPU на контейнер | RAM limit | +| --- | --- | --- | --- | +| API | 2 | 1 | 768 MiB | +| PostgreSQL | 1 | 1 | 512 MiB | +| Valkey | 1 | 0,5 | 256 MiB | +| MinIO | 1 | 1 | 1024 MiB | +| HAProxy | 1 | 0,5 | 128 MiB | +| cleanup | 1 | 0,25 | 256 MiB | +| migrate, только startup | 1 | 0,5 | 256 MiB | +| s3-init, только startup/ручной вызов | 1 | 0,5 | 128 MiB | + +Это верхние ограничения, не резервирование всей указанной памяти. VM и хранилища общие, поэтому измерения зависят от нагрузки Windows/WSL2 и диска. В финальном снимке БД: 157 пользователей, 56 чатов, 13055 сообщений и 13055 idempotency keys; размер БД 15453331 bytes. Данные синтетические, разные тесты используют уникальные пользователей/чаты. + +### Эксперимент уровня 4: десять одновременных загрузок + +Гипотеза: пять upload slots и одно декодирование на реплику позволяют двум API обслужить десять одновременно стартующих клиентов, сохранив конечный расход staging/heap. + +Повторяемая команда: + +```powershell +python -X utf8 student-tests/memory.py +``` + +Методика: два детерминированных PNG с шумом (256×256 и 1536×1536), по одному burst из десяти запросов на размер, без retry. Перед профилем API-контейнеры пересоздаются, сохраняются внешние хранилища и сессия, ожидаются две разные готовые реплики. Клиенты создаются до общего barrier; время burst отсчитывается от его освобождения. Отдельного прогрева upload-ами нет. Kernel lifetime peak включает startup; его сбрасывает создание нового cgroup, а не изменение данных приложения. + +Docker stats сохраняет samples CPU/RAM, дополнительно CLI читает `memory.current` и `memory.peak` cgroup v2. Percentiles считаются методом nearest rank только по успешным запросам. Ошибки и backpressure учитываются отдельно. + +| PNG, bytes / pixels | Concurrency | Успех / запросы | Ошибки | Duration, с | Success RPS | p50 / p95 / p99, мс | +| --- | --- | --- | --- | --- | --- | --- | +| 207687 / 65536 | 10 | 10/10 | 0% | 0.086 | 115.97 | 70.44 / 85.46 / 85.46 | +| 7466790 / 2359296 | 10 | 10/10 | 0% | 2.817 | 3.55 | 1901.06 / 2815.11 / 2815.11 | + +| PNG, bytes | Σ baseline cgroup current, MiB | Σ kernel peaks API, MiB | Максимальный отдельный API peak, MiB | Максимумы CPU API-1 / API-2 в samples | +| --- | --- | --- | --- | --- | +| 207687 | 147.55 | 155.77 | 78.99 | 0.70% / 0.50% | +| 7466790 | 146.18 | 291.10 | 147.04 | 86.90% / 89.15% | + +Наблюдение: оба профиля дали 10/10, 503 — 0; OOMKilled у финальных API не зафиксирован. Гипотеза подтверждена для этих двух burst-профилей. Сумма индивидуальных peak — верхняя оценка одновременного суммарного пика; отдельные максимумы могли возникнуть в разные моменты. CPU samples могут пропускать краткие пики. Размерность предельных 40 млн пикселей этим RAM-экспериментом не покрывалась. + +Raw summary: [upload-memory.json](evidence/upload-memory.json). Ранний профиль с двумя upload slots на API дал 4 успеха и 6 backpressure 503; он сохранён отдельно в [upload-memory-admission-4.json](evidence/upload-memory-admission-4.json). В финальном профиле менялись одновременно admission и возврат страниц MADV_FREE, поэтому сравнение не выделяет причинный эффект одного параметра. + +### Исправление воспроизводимости memory на Windows + +Повторный запуск выявил сбой до самих загрузок: после пересоздания контейнеров `wait_ready(count=2)` не успевал увидеть две разные реплики. Обе API оставались healthy, OOMKilled=false. В диагностической серии шесть запросов к `localhost` заняли примерно 2,04–2,16 с каждый и вернули одну и ту же реплику; шесть запросов к `127.0.0.1` заняли 0,006–0,096 с и показали обе. LB сам обращается к readiness каждые 2 с, поэтому последовательность roundrobin зависит и от этих запросов. + +TCP-проба подтвердила, что `localhost` сначала разрешается в `::1`: отказ IPv6-соединения занимал около 2 с, тогда как соединение с опубликованным `127.0.0.1` устанавливалось за миллисекунды. Сохранены повторяемая методика и фактические локальные TCP-измерения: [memory-readiness-diagnostic.json](evidence/memory-readiness-diagnostic.json). + +Собственный HTTP-клиент и verifier теперь по умолчанию используют опубликованный IPv4 loopback `http://127.0.0.1:8080`; явно заданный `BASE_URL` и прямые адреса контейнеров сохраняются. Readiness probe имеет timeout 2 с и сообщает число увиденных реплик при сбое. Проверка по-прежнему требует две разные готовые API. Публичный клиент и его тесты не изменены. Пять регрессионных проверок выполняются внутри `student-tests/unit.py`; оба реальных memory-профиля и полный verifier затем выполнены заново. Исходный traceback сохранён в [memory-before-ipv4-fix.txt](evidence/memory-before-ipv4-fix.txt), результат повторного запуска — [memory.txt](evidence/memory.txt). + +### Исследование уровня 5: согласованность PostgreSQL и MinIO + +**Гипотеза.** Общий ключ блокировки, проверка durable metadata после получения lock и age threshold позволяют убирать только старые неучтённые объекты; fresh и используемые вложения остаются. Missing-метаданные и ссылки следует сохранить до восстановления оригинала. + +```powershell +# Полная повторяемая инъекция отказов и измерение стоимости: +python -X utf8 student-tests/research.py + +# Обычный CLI: сначала анализ без изменений, затем явный apply: +docker compose exec -T api /messenger reconcile +docker compose exec -T api /messenger reconcile --apply +docker compose exec -T api /messenger reconcile --apply +``` + +**Методика.** Создаются два подтверждённых оригинала, связанные с сообщением. Временный SQL trigger отклоняет INSERT одного уникального синтетического filename после успешного PUT; trigger удаляется в finally. Возникает один новый orphan. Скрипт действительно ждёт 65 секунд для grace 60, не подменяя S3 LastModified. Затем создаёт fresh orphan и удаляет bytes второго подтверждённого вложения, моделируя потерю S3. + +Далее проверяются dry-run без изменений БД/S3, apply, повторный apply, сохранность fresh/used и ссылок сообщения. После восстановления точных bytes повторная сверка проверяет размер и SHA-256. Дополнительно после barrier одновременно запускаются три uploads и apply; каждый подтверждённый upload скачивается и сравнивается. Все воздействия относятся к синтетическим объектам этого стенда. + +**Результат финальной серии:** + +| Этап | Найдено старых orphan | Найдено missing | Удалено объектов | Новых missing-маркеров | Снято маркеров | Внутреннее время, мс | +| --- | --- | --- | --- | --- | --- | --- | +| Dry-run | 1 | 1 | 0 | 0 | 0 | 323 | +| Apply | 1 | 1 | 1 | 1 | 0 | 429 | +| Повтор apply | 0 | 1 | 0 | 0 | 0 | 547 | +| Восстановление | 0 | 0 | 0 | 0 | 1 | 495 | + +В 1 старых orphan входят fixtures предыдущих запусков, успевшие пройти grace; это не число объектов одной инъекции. Dry-run не изменил ни одну сторону. После apply число строк metadata и ссылка missing-вложения остались прежними. Повторный apply не внёс новых изменений. Fresh orphan и используемый original сохранились. При восстановлении потоком проверены 111817 bytes. Проверенный SHA-256 оригинала: `99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75`. + +**Стоимость обхода.** После исправления добавлены 10, затем ещё 100 fresh fixtures; для каждого состояния выполнены три dry-run без дополнительного фиксированного прогрева. Счётчик времени находится внутри reconciler и исключает запуск Docker CLI. В operator CLI используется cgroup API (1 CPU); отдельный периодический cleanup ограничен 0,25 CPU, поэтому его время не приравнивается к operator CLI. + +| Дополнительно создано объектов на этапе | Всего объектов | Metadata rows | HEAD / GET | Время трёх обходов, мс | Медиана, мс | +| --- | --- | --- | --- | --- | --- | +| 10 | 144 | 133 | 141 / 0 | 629, 454, 269 | 454 | +| 100 | 244 | 133 | 241 / 0 | 615, 554, 487 | 554 | + +В более крупном наборе медиана изменилась с 454 до 554 мс, число HEAD — с 141 до 241 при 133 строках metadata. Число операций обхода растёт с набором; по двум небольшим наборам и трём повторам нельзя строить универсальную линейную модель времени. CPU/RAM самого reconciler в отдельный профиль не снимались: здесь измерены elapsed и I/O counters. + +Гипотеза безопасности подтверждена выполненными assert для fresh/used, сохранённых строк/ссылок и повторного apply. В этой серии `active_protected=0`; отдельный детерминированный конфликт удерживаемой lock не измерялся. Raw summary всех стадий и счётчиков: [research.json](evidence/research.json). + +### Дополнительная нагрузка текстовыми сообщениями + +```powershell +python -X utf8 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json +``` + +Генератор closed-loop: четыре клиента начинают следующий POST после ответа на предыдущий, без автоматического retry. Dataset истории растёт; latency включает клиентские издержки, percentiles относятся только к успешным HTTP-подтверждениям. Coordinated omission и ограничение клиента исключают интерпретацию результата как максимальной пропускной способности сервера. + +| Duration заданная / фактическая | Concurrency | Успех / ошибки | Error ratio | Success RPS | p50 / p95 / p99, мс | +| --- | --- | --- | --- | --- | --- | +| 30 / 30.069 с | 4 | 11543 / 0 | 0% | 383.878 | 7.953 / 27.216 / 34.457 | + +Raw summary: [load.json](evidence/load.json). CPU/RAM samples относятся к отдельному upload-эксперименту выше; текстовый генератор сам сохраняет HTTP-метрики, не ресурсный профиль. + +### Диагностика выделения памяти Argon2id + +До корректировки runtime-настройки зафиксированы два timeout публичного клиента (2 с) на регистрации/входе до инъекции отказа. Параметры публичных тестов и Argon2id не менялись. В изолированном контейнере без сети при 1 CPU/768 MiB выполнены пять синтетических Argon2id 64 MiB/t=3/p=1; после каждого вызван `debug.FreeOSMemory`. + +| Режим | Времена KDF, мс | Максимум, мс | System CPU всей серии, с | +| --- | --- | --- | --- | +| По умолчанию | 708.618, 1134.511, 325.256, 385.927, 991.58 | 1134.511 | 2.820411 | +| MADV_FREE | 505.942, 154.841, 220.599, 170.899, 186.14 | 505.942 | 0.356547 | + +Настройка `GODEBUG=madvdontneed=0` уменьшила стоимость повторного выделения страниц в этой серии; освобождённые страницы могут оставаться в RSS до давления по памяти. Окончательный memory-эксперимент и интеграционные проверки повторены именно с ней. Пять samples одного host не доказывают универсальный latency SLA. Исходник — `student-tests/kdf-bench.go.txt`, команды повторения — [MANUAL.md](MANUAL.md), raw summary — [kdf-memory-diagnostic.json](evidence/kdf-memory-diagnostic.json). + +### Отказы и сохранность | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Restart двух API, DB, Valkey, MinIO и LB | Прежние данные и сессия доступны после готовности | Public persistence PASS; ID сохранены, StartedAt изменился у всех 6 контейнеров | Скрипт целиком 16.616 с; отдельный RTO не измерялся; подтверждённые данные сохранены | +| Остановка одной API, серия 1 | Запись через другую реплику ≤10 с, без дублей/потери ACK | 2 реплики до отказа; 132 успешных записей, 4 переходных ошибок | Первая успешная запись через 2.339 с; ACK/сессия/оригинал сохранены | +| Остановка одной API, серия 2 | Запись через другую реплику ≤10 с, без дублей/потери ACK | 2 реплики до отказа; 133 успешных записей, 3 переходных ошибок | Первая успешная запись через 2.312 с; ACK/сессия/оригинал сохранены | +| Остановка именно uploader | Другой API скачивает тот же оригинал | Own test сопоставил upload header с контейнером и сравнил bytes после stop | Отдельный RTO не измерялся; bytes и прежний токен сохранены | +| Недоступен S3 | Liveness 200, readiness/upload/content 503 | Ожидаемые коды непосредственно на API; после start оригинал читается | Отдельный RTO не измерялся; данные volume сохранены | +| Разрыв тела upload | Нет готовых metadata для неполного файла | Число metadata не изменилось | ACK не выдавался; новый готовый Attachment не создан | +| SQL-ошибка после PUT | Orphan обнаруживается после grace | Dry-run находит, apply безопасно очищает | Эксперимент ждёт реальные 65 с; подтверждённые вложения не удалены | +| Потеря bytes S3 после 201 | Metadata/ссылки остаются, отсутствие не маскируется | Missing помечен, участник получает 503 | До восстановления оригинала bytes недоступны; после SHA-256 marker снят | +| Повтор bootstrap | Не менять секреты и не терять original | Два запуска PASS, файл тот же | Потерь не зафиксировано | + +Доказательства: `evidence/persistence.txt`, `failover-1.txt`, `failover-2.txt`, `failures.json`, `research.json` и hook snapshots, на которые даны ссылки выше. Числа failover относятся к первой восстановленной записи данного теста, а не к production RTO всего стенда. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +### Граница применимости результатов + +Один Docker-host не обеспечивает отказоустойчивость физического узла. LB, PostgreSQL, Valkey и MinIO остаются отдельными точками отказа. Named volumes и fsync дают проверенную сохранность при описанном restart, но не заменяют backup и не защищают от удаления volume или утраты диска. HTTP допустим только для локального стенда с синтетическими данными; TLS/mTLS и ротация секретов в эту лабораторную не входят. + +MinIO Community архивирован. Отдельный binary-mode scan исходной сборки содержит 52 module-level записи; он не доказывает достижимость всех функций в конкретном стенде. Внешние воздействия ограничены private backend, закрытой консолью и фильтрами HAProxy, но это не полное исправление стороннего сервера и не production-сертификация. Scan собственного приложения показал 0 уязвимостей в вызываемом коде, при этом три записи остались на уровне невызываемых модулей. Сферы этих двух результатов нельзя смешивать. + +Фильтр отклоняет `STREAMING-UNSIGNED-PAYLOAD-TRAILER`, storage/peer/grid/bootstrap REST-пути, S3 Select и replication-request headers. Это неиспользуемые функции выбранного стенда; LDAP/OIDC/SFTP не настроены. Контейнер из общей сети не смог обратиться непосредственно к IP MinIO backend. Сервисный S3 listener не пишет URL в журнал, чтобы admin/bootstrap query не раскрывал identifiers ключей. + +Между БД и S3 сохраняется окно рассогласованности. Cleanup уменьшает его периодической сверкой, но при недоступных зависимостях исправление откладывается. Missing bytes невозможно получить из metadata: нужна внешняя копия. Обычный проход не выполняет полный SHA-256 каждого ready-объекта. Прямая администраторская запись в S3 вне протокола API не координируется advisory lock. Часы PostgreSQL/MinIO должны быть согласованы. + +Upload RAM проверена для двух размеров, 10 клиентов и одной серии на размер, а не для всех допустимых изображений вплоть до 40 млн пикселей. Рабочие буферы декодера и GC требуют памяти помимо пиксельного массива; мягкий heap limit не равен RSS. Cgroup остаётся последним ограничителем ресурсов. Указанные percentiles и RPS не являются универсальными порогами или пределом производительности; для статистических выводов нужны дополнительные независимые повторы. + +### Что подтверждено и что требует отдельной работы + +| Подтверждено в этой работе | Следующий шаг / граница, которая пока не доказана | +| --- | --- | +| Restart с сохранёнными volumes сохраняет ACK, original и сессию | Проверяемый backup/restore после потери диска | +| Отказ одной API выдерживается с восстановлением записи ≤10 с | HA хранилищ, LB и host на независимых узлах | +| Old orphan очищаются, fresh/used не удаляются в выполненных сценариях | Детерминированный тест именно конфликта удерживаемой lock; крупные длительные наборы | +| Missing marker снимается только после правильного размера/SHA-256 | Полный аудит integrity всех ready originals и автоматизированное восстановление из backup | +| Два профиля по 10 uploads завершились без ошибок | Повторы под длительной/open-loop нагрузкой и отдельное исследование предельной размерности | +| MADV_FREE уменьшил kernel cost в диагностической серии | Проверка этой настройки на других host и под давлением памяти | +| Private bucket, IAM и proxy filters проверены | Продолжающийся аудит и сопровождение MinIO/dependencies; защита всего Docker-host | +| Контракт и public tests не изменялись | Итоговый commit/push и публикация PR — отдельное действие автора | + +Прямой presigned-upload flow не реализован, поскольку выбран трек 2. Фоновые worker/thumbnail и переход на 202 относятся к следующей лабораторной. При исправлении readiness изменены собственный Python-клиент и verifier; Go-код приложения, контракт и публичные тесты сохранены. Таблицы обновлены по новому полному прогону. + +## Дополнительные материалы + +### Короткий сценарий защиты + +1. Запустить `python -X utf8 scripts/manage.py start`, показать два реальных API через `status` и `X-Instance-Id`. +2. По [MANUAL.md](MANUAL.md) создать Alice/Bob/Eve, загрузить PNG, отправить `attachment_ids`, скачать Bob и сравнить SHA-256. Для Eve показать 404; анонимный запрос в private S3 даёт 403. +3. Остановить именно uploader по alias, скачать через другую реплику с прежним токеном, затем восстановить две реплики. +4. Показать public persistence и StartedAt before/after для DB/Valkey/MinIO/API, не удаляя volumes. +5. Показать dry-run, apply и повтор, `research.json`, сохранённые missing metadata/ссылки и восстановление по checksum. +6. Открыть таблицу 10/10 uploads, объяснить разницу между memory.peak, суммой индивидуальных peaks и фактическим общим пиком в один момент. + +### Ответы на вопросы + +**Почему local volume API не заменяет S3?** Файл отдельной реплики не обязан быть доступен другой реплике. Здесь durable original хранится в общем MinIO, а tmpfs API содержит только временный staging запроса. + +**Когда допустим 201?** После сохранения bytes и успешного COMMIT metadata. До этой границы нельзя обещать клиенту готовое вложение, доступное другой реплике. + +**Почему не удалить файл сразу после ошибки COMMIT?** Ответ о COMMIT мог потеряться после фактической фиксации. Такой DELETE повредил бы существующий Attachment. Reconciler после grace проверяет durable состояние под lock. + +**Что означают orphan, missing и grace period?** Orphan — объект есть, строки нет; missing — строка есть, bytes нет. Grace — минимальный возраст перед исправлением, чтобы свежий объект не приняли за остаток аварии. В обычном режиме grace час; в контролируемом опыте 60 секунд с реальным ожиданием 65. + +**Зачем ACL, если UUID случайный и bucket private?** UUID скрывает угадывание, а private bucket закрывает прямое чтение. Права на чат всё равно проверяет API для каждого metadata/content/message запроса; секретная ссылка не заменяет членство. + +**Почему SHA-256 файла не подходит для пароля?** SHA-256 здесь проверяет равенство bytes. Для пароля нужна дорогая salted KDF, поэтому используется Argon2id; одинаковые пароли получают разные salts/hashes. + +**Что именно доказано повторным apply?** Без новых отказов он не удалил дополнительных объектов и не создал повторных missing-маркеров. Это идемпотентность конкретных операций; она не означает, что bytes можно восстановить без копии. + +**Почему 503 от LB может быть без JSON API?** При отсутствии ready backend ответ создаёт балансировщик. Тест отказа S3 отдельно обращается к внутреннему API и проверяет его JSON error/request_id. + +### Карта файлов решения + +| Файлы | Назначение | +| --- | --- | +| `main.go`, `protocol.go` | HTTP routing/headers, строгий JSON, cursor и общий lifecycle | +| `auth.go`, `auth_test.go` | Argon2id, Bearer/Valkey sessions и проверки базовой защиты | +| `store.go`, `idempotency.go` | PostgreSQL, history, транзакционная запись и результат повтора | +| `attachments.go`, `migrations/004_attachments.sql` | Валидация/MinIO, metadata и связи сообщений | +| `reconcile.go`, `memory.go` | Сверка/cleanup и локальный CLI cgroup memory snapshot | +| `compose.yaml`, `Dockerfile*` | Воспроизводимый стенд, app/S3/test images | +| `infra/haproxy.cfg`, `infra/s3-init.sh`, `infra/s3-policy.json` | Балансировка/фильтры, private bucket и IAM | +| `scripts/bootstrap.py`, `manage.py`, `restart.sh`, `stop-one.sh` | Создание локальных настроек и операторские действия | +| `scripts/verify.py`, `summarize.py` | Последовательная проверка и фактическая сводка | +| `student-tests/` | Own unit, negative/failure, memory и track 2 research | +| `MANUAL.md`, `.github/pull_request_template.md` | Пошаговые команды и заполненный PR шаблон | + +### Источники и сохранённые данные + +- Нормативные требования: [README.md](README.md), [COURSE.md](COURSE.md), [контракт](contracts/README.md), [OpenAPI](contracts/openapi.json). +- Собственная HLAlab3: исходники, миграции, общие сессии, балансировка и идемпотентность; контракты/публичные tests текущей lab4 оставлены её собственными. +- Официальные материалы: [MinIO](https://github.com/minio/minio), [защитная мера unsigned-trailer](https://github.com/minio/minio/security/advisories/GHSA-hv4r-mvr4-25vw), [MinIO Go SDK](https://pkg.go.dev/github.com/minio/minio-go/v7), [Go image](https://pkg.go.dev/image#hdr-Security_Considerations), [Go runtime](https://pkg.go.dev/runtime#hdr-Environment_Variables). +- Отдельный сторонний scan MinIO: [minio-upstream-vulnerabilities.txt](evidence/minio-upstream-vulnerabilities.txt). Он не подменяет scan приложения. +- Итоговый audit отсутствия значений локальных секретов в Git-visible текстах: [final-local-checks.json](evidence/final-local-checks.json). Git ignore не заменяет этот просмотр; `.env`, `secrets/`, приватные ключи и временные binaries не добавляются в commit. + +Доказательства содержат синтетические данные и operational fields, без паролей, Bearer-токенов, приватных ключей или подписанных URL. Итоговые числа не заменены ожидаемыми: каждый PASS привязан к команде и наблюдению. diff --git a/attachments.go b/attachments.go new file mode 100644 index 00000000..9d05cb4a --- /dev/null +++ b/attachments.go @@ -0,0 +1,287 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "image" + _ "image/jpeg" + _ "image/png" + "io" + "mime" + "net" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/jackc/pgx/v5" + "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" +) + +const maxUploadBytes int64 = 10 * 1024 * 1024 +const maxImagePixels int64 = 40000000 + +type Attachment struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + OwnerID string `json:"owner_id"` + Filename string `json:"filename"` + ContentType string `json:"content_type"` + SizeBytes int64 `json:"size_bytes"` + SHA256 string `json:"sha256"` + Status string `json:"status"` + Variants []any `json:"variants"` + ErrorCode *string `json:"error_code"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +func s3Client() (*minio.Client, string, error) { + endpoint, err := url.Parse(env("S3_ENDPOINT", "http://s3:9000")) + if err != nil || (endpoint.Scheme != "http" && endpoint.Scheme != "https") || endpoint.Host == "" || endpoint.User != nil || endpoint.RawQuery != "" || (endpoint.Path != "" && endpoint.Path != "/") { + return nil, "", errors.New("invalid S3 endpoint") + } + access, err := secretFile("S3_ACCESS_KEY_ID_FILE") + if err != nil { + return nil, "", err + } + secret, err := secretFile("S3_SECRET_ACCESS_KEY_FILE") + if err != nil { + return nil, "", err + } + transport := &http.Transport{Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{Timeout: 2 * time.Second, KeepAlive: 30 * time.Second}).DialContext, MaxIdleConns: 16, MaxIdleConnsPerHost: 8, MaxConnsPerHost: 8, ResponseHeaderTimeout: 5 * time.Second, TLSHandshakeTimeout: 3 * time.Second, IdleConnTimeout: 30 * time.Second, DisableCompression: true} + client, err := minio.New(endpoint.Host, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: endpoint.Scheme == "https", Region: env("S3_REGION", "us-east-1"), Transport: transport, MaxRetries: 1, BucketLookup: minio.BucketLookupPath}) + return client, env("S3_BUCKET", "messenger-attachments"), err +} + +func validFilename(s string) bool { + if !utf8.ValidString(s) || strings.TrimSpace(s) == "" || utf8.RuneCountInString(s) > 255 { + return false + } + for _, c := range s { + if c == '/' || c == '\\' || unicode.IsControl(c) { + return false + } + } + return true +} + +func messageFields(body map[string]json.RawMessage) (string, []string, error) { + var text string + if string(body["text"]) == "null" || json.Unmarshal(body["text"], &text) != nil || utf8.RuneCountInString(text) > 4000 { + return "", nil, invalid() + } + ids := []string{} + if raw, ok := body["attachment_ids"]; ok { + if string(raw) == "null" || json.Unmarshal(raw, &ids) != nil || len(ids) > 10 { + return "", nil, invalid() + } + } + seen := map[string]bool{} + for i, id := range ids { + normalized, err := normalizeID(id) + if err != nil || seen[normalized] { + return "", nil, invalid() + } + ids[i] = normalized + seen[normalized] = true + } + if strings.TrimSpace(text) == "" && len(ids) == 0 { + return "", nil, invalid() + } + return text, ids, nil +} + +func (a *App) s3Ready(ctx context.Context) bool { + check, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + ok, err := a.s3.BucketExists(check, a.bucket) + return err == nil && ok +} +func mediaError() error { + return apiError{415, "unsupported_media_type", "Expected a valid PNG or JPEG matching Content-Type"} +} +func tooLarge() error { return apiError{413, "payload_too_large", "Image exceeds byte or pixel limit"} } + +// The encoded file lives only in a bounded tmpfs during validation/PUT. At most +// five uploads and one decoded image per process; no bytes enter PostgreSQL. +func (a *App) upload(ctx context.Context, w http.ResponseWriter, r *http.Request, chat, user string) (Attachment, error) { + result := Attachment{} + query, err := url.ParseQuery(r.URL.RawQuery) + if err != nil || len(query) != 1 || len(query["filename"]) != 1 || !validFilename(query.Get("filename")) { + return result, invalid() + } + contentType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || len(params) != 0 || (contentType != "image/png" && contentType != "image/jpeg") { + return result, mediaError() + } + if r.ContentLength > maxUploadBytes { + return result, tooLarge() + } + select { + case a.uploadSlots <- struct{}{}: + defer func() { <-a.uploadSlots }() + default: + return result, unavailable() + } + f, err := os.CreateTemp("", "upload-*") + if err != nil { + return result, unavailable() + } + defer os.Remove(f.Name()) + defer f.Close() + digest := sha256.New() + size, err := io.Copy(io.MultiWriter(f, digest), http.MaxBytesReader(w, r.Body, maxUploadBytes)) + if err != nil { + var big *http.MaxBytesError + if errors.As(err, &big) { + return result, tooLarge() + } + return result, invalid() + } + if size == 0 { + return result, mediaError() + } + if _, err = f.Seek(0, io.SeekStart); err != nil { + return result, unavailable() + } + cfg, format, err := image.DecodeConfig(f) + if err != nil || (format != "png" && format != "jpeg") || "image/"+format != contentType { + return result, mediaError() + } + if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width) > maxImagePixels/int64(cfg.Height) { + return result, tooLarge() + } + select { + case a.decodeSlot <- struct{}{}: + case <-ctx.Done(): + return result, unavailable() + } + validation := func() error { + defer func() { <-a.decodeSlot }() + if _, e := f.Seek(0, io.SeekStart); e != nil { + return unavailable() + } + decoded, actual, e := image.Decode(f) + if e != nil || actual != format || decoded.Bounds().Dx() != cfg.Width || decoded.Bounds().Dy() != cfg.Height { + return mediaError() + } + return nil + } + if err = validation(); err != nil { + return result, err + } + if ctx.Err() != nil { + return result, unavailable() + } + if _, err = f.Seek(0, io.SeekStart); err != nil { + return result, unavailable() + } + result = Attachment{ID: uuid(), ChatID: chat, OwnerID: user, Filename: query.Get("filename"), ContentType: contentType, SizeBytes: size, SHA256: hex.EncodeToString(digest.Sum(nil)), Status: "ready", Variants: []any{}} + tx, err := a.db.Begin(ctx) + if err != nil { + return result, unavailable() + } + defer rollbackAttachment(tx) + if err = attachmentLock(ctx, tx, result.ID); err != nil { + return result, unavailable() + } + key := "original/" + result.ID + _, err = a.s3.PutObject(ctx, a.bucket, key, f, size, minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true, UserMetadata: map[string]string{"sha256": result.SHA256}}) + if err != nil { + return result, unavailable() + } + var created, updated time.Time + err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,owner_id,object_key,filename,content_type,size_bytes,sha256) + VALUES($1,$2,$3,$4,$5,$6,$7,$8) RETURNING created_at,updated_at`, result.ID, chat, user, key, result.Filename, contentType, size, result.SHA256).Scan(&created, &updated) + if err != nil { + return result, unavailable() + } + // COMMIT may have succeeded even when its acknowledgement is lost. Never + // blindly delete the blob here: reconciler checks durable metadata + grace. + if err = tx.Commit(ctx); err != nil { + return result, unavailable() + } + result.CreatedAt = stamp(created) + result.UpdatedAt = stamp(updated) + return result, nil +} + +func attachmentLock(ctx context.Context, tx pgx.Tx, id string) error { + _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", "attachment:"+id) + return err +} + +func rollbackAttachment(tx pgx.Tx) { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _ = tx.Rollback(ctx) +} + +func (a *App) attachment(ctx context.Context, id, user string) (Attachment, error) { + x := Attachment{Status: "ready", Variants: []any{}} + var created, updated time.Time + var missingSince *time.Time + err := a.db.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.owner_id::text,a.filename,a.content_type,a.size_bytes,a.sha256,a.created_at,a.updated_at,a.missing_since + FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id AND m.user_id=$2 WHERE a.id=$1`, id, user).Scan(&x.ID, &x.ChatID, &x.OwnerID, &x.Filename, &x.ContentType, &x.SizeBytes, &x.SHA256, &created, &updated, &missingSince) + if err != nil { + return x, dbError(err) + } + if missingSince != nil { + return x, unavailable() + } + x.CreatedAt = stamp(created) + x.UpdatedAt = stamp(updated) + return x, nil +} + +type binaryContent struct { + attachment Attachment + object *minio.Object +} + +func (a *App) content(ctx context.Context, r *http.Request, x Attachment) (binaryContent, error) { + q, err := url.ParseQuery(r.URL.RawQuery) + if err != nil || len(q) > 1 || len(q["variant"]) > 1 { + return binaryContent{}, invalid() + } + for k := range q { + if k != "variant" { + return binaryContent{}, invalid() + } + } + if v, ok := q["variant"]; ok && v[0] != "original" { + return binaryContent{}, missing() + } + object, err := a.s3.GetObject(ctx, a.bucket, "original/"+x.ID, minio.GetObjectOptions{}) + if err != nil { + return binaryContent{}, unavailable() + } + info, err := object.Stat() + if err != nil || info.Size != x.SizeBytes { + object.Close() + return binaryContent{}, unavailable() + } + return binaryContent{x, object}, nil +} + +func writeContent(w http.ResponseWriter, b binaryContent) { + defer b.object.Close() + w.Header().Set("Content-Type", b.attachment.ContentType) + w.Header().Set("Content-Length", strconv.FormatInt(b.attachment.SizeBytes, 10)) + w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": b.attachment.Filename})) + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Cache-Control", "private, no-store") + w.WriteHeader(200) + if _, err := io.CopyN(w, b.object, b.attachment.SizeBytes); err != nil { + panic(http.ErrAbortHandler) + } +} diff --git a/auth.go b/auth.go new file mode 100644 index 00000000..663bc947 --- /dev/null +++ b/auth.go @@ -0,0 +1,147 @@ +package main + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "strings" + "time" + "unicode/utf8" + + "github.com/jackc/pgx/v5" + "github.com/redis/go-redis/v9" + "golang.org/x/crypto/argon2" +) + +func password(body map[string]json.RawMessage) (string, error) { + var p string + if json.Unmarshal(body["password"], &p) != nil || utf8.RuneCountInString(p) < 12 || utf8.RuneCountInString(p) > 128 { + return "", invalid() + } + return p, nil +} +func hashPassword(p string) string { + salt := make([]byte, 16) + if _, err := rand.Read(salt); err != nil { + panic(err) + } + key := argon2.IDKey([]byte(p), salt, 3, 64*1024, 1, 32) + return "$argon2id$v=19$m=65536,t=3,p=1$" + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(key) +} +func verifyPassword(hash, p string) bool { + parts := strings.Split(hash, "$") + if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" || parts[3] != "m=65536,t=3,p=1" { + return false + } + salt, e := base64.RawStdEncoding.DecodeString(parts[4]) + if e != nil || len(salt) != 16 { + return false + } + want, e := base64.RawStdEncoding.DecodeString(parts[5]) + if e != nil || len(want) != 32 { + return false + } + actual := argon2.IDKey([]byte(p), salt, 3, 64*1024, 1, 32) + return subtle.ConstantTimeCompare(want, actual) == 1 +} +func (a *App) kdfSlot(ctx context.Context) error { + select { + case a.kdf <- struct{}{}: + return nil + case <-ctx.Done(): + return unavailable() + } +} + +type storedSession struct { + UserID string `json:"user_id"` + ExpiresAt time.Time `json:"expires_at"` +} + +func sessionKey(token string) string { + h := sha256.Sum256([]byte(token)) + return "sess:" + hex.EncodeToString(h[:]) +} +func (a *App) authenticate(ctx context.Context, r *http.Request) (string, string, error) { + values := r.Header.Values("Authorization") + if len(values) != 1 { + return "", "", unauthorized() + } + parts := strings.Fields(values[0]) + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { + return "", "", unauthorized() + } + token, e := base64.RawURLEncoding.DecodeString(parts[1]) + if e != nil || len(token) != 32 { + return "", "", unauthorized() + } + key := sessionKey(parts[1]) + raw, err := a.sessions.Get(ctx, key).Bytes() + if errors.Is(err, redis.Nil) { + return "", "", unauthorized() + } + if err != nil { + return "", "", unavailable() + } + var session storedSession + if json.Unmarshal(raw, &session) != nil { + return "", "", unavailable() + } + if !time.Now().Before(session.ExpiresAt) { + return "", "", unauthorized() + } + if _, err = a.user(ctx, session.UserID); err != nil { + var ae apiError + if errors.As(err, &ae) && ae.status == 404 { + return "", "", unauthorized() + } + return "", "", err + } + return session.UserID, key, nil +} +func (a *App) login(ctx context.Context, r *http.Request) (int, any, error) { + if r.ContentLength > 0 || len(r.TransferEncoding) > 0 { + return 0, nil, invalid() + } + username, p, ok := r.BasicAuth() + if len(r.Header.Values("Authorization")) != 1 || !ok || !usernamePattern.MatchString(username) || !utf8.ValidString(p) || utf8.RuneCountInString(p) < 12 || utf8.RuneCountInString(p) > 128 { + return 0, nil, unauthorized() + } + var hash string + var u User + var created time.Time + err := a.db.QueryRow(ctx, "SELECT id::text,username,display_name,created_at,password_hash FROM users WHERE username=$1", username).Scan(&u.ID, &u.Username, utf8String{&u.DisplayName}, &created, &hash) + absent := errors.Is(err, pgx.ErrNoRows) + if err != nil && !absent { + return 0, nil, unavailable() + } + if absent { + hash = a.dummyHash + } + if err = a.kdfSlot(ctx); err != nil { + return 0, nil, err + } + valid := verifyPassword(hash, p) + <-a.kdf + if !valid || absent { + return 0, nil, unauthorized() + } + u.CreatedAt = stamp(created) + tokenBytes := make([]byte, 32) + if _, err = rand.Read(tokenBytes); err != nil { + return 0, nil, unavailable() + } + token := base64.RawURLEncoding.EncodeToString(tokenBytes) + expires := time.Now().UTC().Truncate(time.Second).Add(a.ttl) + raw, _ := json.Marshal(storedSession{u.ID, expires}) + if err = a.sessions.SetArgs(ctx, sessionKey(token), raw, redis.SetArgs{Mode: "NX", ExpireAt: expires}).Err(); err != nil { + return 0, nil, unavailable() + } + return 201, map[string]any{"token": token, "token_type": "Bearer", "expires_at": expires.Format(time.RFC3339), "user": u}, nil +} diff --git a/auth_test.go b/auth_test.go new file mode 100644 index 00000000..0ee95195 --- /dev/null +++ b/auth_test.go @@ -0,0 +1,50 @@ +package main + +import ( + "net/http/httptest" + "strings" + "testing" +) + +func TestPasswordHashSaltAndFullUnicode(t *testing.T) { + p := strings.Repeat("😀", 127) + ":" + a, b := hashPassword(p), hashPassword(p) + if a == b { + t.Fatal("salt reused") + } + if !verifyPassword(a, p) || verifyPassword(a, strings.Repeat("😀", 127)+"!") { + t.Fatal("password truncated or incorrect") + } + for _, bad := range []string{"", p, strings.Replace(a, "m=65536", "m=1", 1), a[:len(a)-5]} { + if verifyPassword(bad, p) { + t.Fatal("invalid hash accepted") + } + } +} + +func TestCursorIntegrityResourceAndRestart(t *testing.T) { + a := &App{secret: []byte("stable-local-test-secret-32-bytes")} + encoded := a.encodeCursor("messages:one", "2026-01-01T00:00:00.000000Z", uuid()) + restarted := &App{secret: append([]byte(nil), a.secret...)} + req := httptest.NewRequest("GET", "/messages?cursor="+encoded+"&limit=7", nil) + if limit, _, e := restarted.pagination(req, "messages:one"); e != nil || limit != 7 { + t.Fatal("cursor lost across restart") + } + if _, _, e := a.pagination(req, "messages:two"); e == nil { + t.Fatal("cross-resource cursor accepted") + } + forged := httptest.NewRequest("GET", "/messages?cursor="+encoded[:len(encoded)-4]+"AAAA", nil) + if _, _, e := a.pagination(forged, "messages:one"); e == nil { + t.Fatal("forged cursor accepted") + } +} + +func TestStrictJSON(t *testing.T) { + for _, raw := range []string{`{"text":"a","text":"b"}`, `{"text":"\ud800"}`, `{} {}`, `{"unknown":1}`} { + req := httptest.NewRequest("POST", "/", strings.NewReader(raw)) + req.Header.Set("Content-Type", "application/json") + if _, e := readObject(httptest.NewRecorder(), req, 1024, []string{"text"}); e == nil { + t.Fatalf("accepted %q", raw) + } + } +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..6de35fca --- /dev/null +++ b/compose.yaml @@ -0,0 +1,194 @@ +name: mtusi-lab4 +services: + db: + image: postgres:17.6-bookworm@sha256:f3bd19c606e442c3d7bdfa8002e03fe260a1023351e0ea4598032022b68dd6e3 + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: [postgres_password] + volumes: [pgdata:/var/lib/postgresql/data] + healthcheck: + test: [CMD-SHELL, "pg_isready -U messenger -d messenger"] + interval: 2s + timeout: 2s + retries: 30 + mem_limit: 512m + cpus: ${DB_CPUS:-1.0} + valkey: + image: valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571 + command: [valkey-server, /run/secrets/valkey_config] + secrets: [valkey_config, valkey_password] + volumes: [sessions:/data] + healthcheck: + test: [CMD-SHELL, 'REDISCLI_AUTH="$$(cat /run/secrets/valkey_password)" valkey-cli ping | grep -q PONG'] + interval: 2s + timeout: 2s + retries: 30 + mem_limit: 256m + cpus: 0.5 + migrate: + image: mtusi-messenger:lab4 + build: . + command: [migrate] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + secrets: [database_url] + depends_on: + db: {condition: service_healthy} + mem_limit: 256m + cpus: 0.5 + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + api: + image: mtusi-messenger:lab4 + build: . + deploy: + replicas: ${API_REPLICAS:-2} + environment: + APP_HOST: ${APP_HOST:-0.0.0.0} + APP_PORT: 8080 + APP_ENV: ${APP_ENV:-lab} + SESSION_STORE: ${SESSION_STORE:-valkey} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + DB_POOL_MAX: ${DB_POOL_MAX:-8} + MAX_INFLIGHT: ${MAX_INFLIGHT:-32} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + GOMEMLIMIT: ${GOMEMLIMIT:-512MiB} + GODEBUG: madvdontneed=0 + POOL_METRICS: ${POOL_METRICS:-0} + REQUEST_LOG: ${REQUEST_LOG:-1} + DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url} + CACHE_URL_FILE: ${CACHE_URL_FILE:-/run/secrets/cache_url} + CURSOR_SECRET_FILE: ${CURSOR_SECRET_FILE:-/run/secrets/cursor_secret} + S3_ENDPOINT: http://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 + secrets: [database_url, cache_url, cursor_secret, s3_access_key_id, s3_secret_access_key] + tmpfs: ["/tmp:size=64m,mode=1777,noexec,nosuid,nodev"] + depends_on: + db: {condition: service_healthy} + valkey: {condition: service_healthy} + migrate: {condition: service_completed_successfully} + s3-init: {condition: service_completed_successfully} + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: ${API_MEMORY:-768m} + cpus: ${API_CPUS:-1.0} + pids_limit: 128 + logging: + options: {max-size: 10m, max-file: "2"} + stop_grace_period: 10s + s3: + image: mtusi-minio:RELEASE.2025-10-15T17-29-55Z + build: + context: . + dockerfile: Dockerfile.minio + command: [server, /data, --console-address, "127.0.0.1:9001"] + environment: + MINIO_ROOT_USER_FILE: /run/secrets/s3_root_user + MINIO_ROOT_PASSWORD_FILE: /run/secrets/s3_root_password + MINIO_BROWSER: "off" + secrets: [s3_root_user, s3_root_password] + volumes: [objects:/data] + networks: + object_store: + aliases: [minio-backend] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: 1g + cpus: 1.0 + healthcheck: + test: [CMD, /healthcheck] + interval: 2s + timeout: 2s + retries: 60 + s3-init: + image: mtusi-minio-tools:RELEASE.2025-08-13T08-35-41Z + build: + context: . + dockerfile: Dockerfile.minio + target: tools + entrypoint: [/bin/sh, /bootstrap/s3-init.sh] + secrets: [s3_root_user, s3_root_password, s3_access_key_id, s3_secret_access_key] + volumes: [./infra/s3-init.sh:/bootstrap/s3-init.sh:ro, ./infra/s3-policy.json:/bootstrap/policy.json:ro] + depends_on: + s3: {condition: service_healthy} + lb: {condition: service_started} + tmpfs: ["/tmp:size=16m,mode=1777,noexec,nosuid,nodev"] + environment: {MC_CONFIG_DIR: /tmp/mc} + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: 128m + cpus: 0.5 + cleanup: + image: mtusi-messenger:lab4 + build: . + command: [reconcile-loop] + restart: unless-stopped + environment: + DATABASE_URL_FILE: /run/secrets/database_url + S3_ENDPOINT: http://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 + secrets: [database_url, s3_access_key_id, s3_secret_access_key] + depends_on: + db: {condition: service_healthy} + migrate: {condition: service_completed_successfully} + s3-init: {condition: service_completed_successfully} + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: 256m + cpus: 0.25 + healthcheck: {disable: true} + logging: + options: {max-size: 10m, max-file: "2"} + lb: + image: haproxy:3.2.6-alpine + ports: ["127.0.0.1:${APP_PORT:-8080}:8080"] + volumes: [./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro] + depends_on: + s3: {condition: service_healthy} + networks: + default: + aliases: [s3] + object_store: {} + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: 128m + cpus: 0.5 + stop_grace_period: 10s + logging: + options: {max-size: 10m, max-file: "2"} + healthcheck: + test: [CMD-SHELL, "wget -q -O /dev/null http://127.0.0.1:8080/health/ready"] + interval: 2s + timeout: 2s + retries: 30 +networks: + object_store: + internal: true +volumes: + pgdata: + sessions: + objects: +secrets: + postgres_password: {file: ./secrets/postgres_password} + database_url: {file: ./secrets/database_url} + valkey_password: {file: ./secrets/valkey_password} + valkey_config: {file: ./secrets/valkey.conf} + cache_url: {file: ./secrets/cache_url} + cursor_secret: {file: ./secrets/cursor_secret} + s3_root_user: {file: ./secrets/s3_root_user} + s3_root_password: {file: ./secrets/s3_root_password} + s3_access_key_id: {file: ./secrets/s3_access_key_id} + s3_secret_access_key: {file: ./secrets/s3_secret_access_key} diff --git a/evidence/RESULTS.md b/evidence/RESULTS.md new file mode 100644 index 00000000..04a825c8 --- /dev/null +++ b/evidence/RESULTS.md @@ -0,0 +1,56 @@ +# Фактические результаты lab4 + +Полный прогон завершён: **да**. +Контракт и публичные тесты неизменны: True. + +| Проверка | Exit code | Время, с | +| --- | --- | --- | +| contract | 0 | 0.138 | +| go-test | 0 | 5.41 | +| go-vet | 0 | 0.78 | +| student-unit | 0 | 8.884 | +| go-vuln | 0 | 4.982 | +| bootstrap | 0 | 0.108 | +| compose-config | 0 | 0.532 | +| start | 0 | 22.452 | +| build-tests | 0 | 1.33 | +| openapi | 0 | 3.173 | +| go-race | 0 | 50.4 | +| smoke | 0 | 6.144 | +| attachments | 0 | 2.309 | +| persistence | 0 | 16.616 | +| ready-before-failover | 0 | 4.723 | +| failover-1 | 0 | 18.656 | +| restore-1 | 0 | 2.349 | +| failover-2 | 0 | 17.823 | +| restore-2 | 0 | 1.614 | +| failures | 0 | 30.976 | +| memory | 0 | 28.649 | +| research | 0 | 120.647 | +| load | 0 | 35.234 | +| infrastructure | 0 | 3.879 | + +## 10 одновременно стартующих uploads + +| Bytes | Успех | 503 | RPS успешных | p95, мс | Σ cgroup peak, MiB | +| --- | --- | --- | --- | --- | --- | +| 207687 | 10 | 0 | 115.97 | 85.46 | 155.77 | +| 7466790 | 10 | 0 | 3.55 | 2815.11 | 291.10 | + +Сумма отдельных kernel peaks — верхняя оценка одновременного общего пика. Startup включён. + +## Согласованность DB/S3 + +| Этап | Orphan | Missing | Удалено | Отмечено | Восстановлено | +| --- | --- | --- | --- | --- | --- | +| dry_run | 1 | 1 | 0 | 0 | 0 | +| apply | 1 | 1 | 1 | 1 | 0 | +| repeat_apply | 0 | 1 | 0 | 0 | 0 | +| recovery | 0 | 0 | 0 | 0 | 1 | + +| Добавлено объектов | Объектов всего | Metadata rows | HEAD requests | Время обхода, мс (3 повтора) | +| --- | --- | --- | --- | --- | +| 10 | 144 | 133 | 141 | 629, 454, 269 | +| 100 | 244 | 133 | 241 | 615, 554, 487 | + +Каждый PASS опирается на журнал соответствующей команды. Отсутствующие результаты не считаются выполненными. diff --git a/evidence/attachments.json b/evidence/attachments.json new file mode 100644 index 00000000..813581fb --- /dev/null +++ b/evidence/attachments.json @@ -0,0 +1,12 @@ +{ + "complete": true, + "passed": [ + "byte limit before decode", + "corrupt, empty, MIME spoof", + "pixel limit before full decode", + "unsafe filename", + "foreign attachment and chat ACL", + "attachment-only, text-only, replay, concurrent replay, exact download", + "real JPEG exact download" + ] +} diff --git a/evidence/attachments.txt b/evidence/attachments.txt new file mode 100644 index 00000000..513b753d --- /dev/null +++ b/evidence/attachments.txt @@ -0,0 +1 @@ +PASS attachment validation, ACL and compatibility diff --git a/evidence/contract.txt b/evidence/contract.txt new file mode 100644 index 00000000..b62af9c5 --- /dev/null +++ b/evidence/contract.txt @@ -0,0 +1 @@ +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/evidence/failover-1.txt b/evidence/failover-1.txt new file mode 100644 index 00000000..e841641e --- /dev/null +++ b/evidence/failover-1.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://lb:8080" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 132, "failed_attempts": 4, "first_recovery_seconds": 2.339} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/failover-2.txt b/evidence/failover-2.txt new file mode 100644 index 00000000..ed6ae576 --- /dev/null +++ b/evidence/failover-2.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://lb:8080" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 133, "failed_attempts": 3, "first_recovery_seconds": 2.312} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/failures.json b/evidence/failures.json new file mode 100644 index 00000000..71224888 --- /dev/null +++ b/evidence/failures.json @@ -0,0 +1,12 @@ +{ + "complete": true, + "passed": [ + "private bucket anonymous GET: 403", + "unsigned trailers, storage REST, S3 Select and replication headers blocked at private proxy", + "API account cannot administer, create bucket or write outside original/", + "idempotent bootstrap preserves data and credentials", + "S3 outage: live 200, ready/upload/content 503, restart retains bytes", + "exact uploading container stopped; another replica returned identical original with old session", + "interrupted body creates no metadata; dependency recovers" + ] +} diff --git a/evidence/failures.txt b/evidence/failures.txt new file mode 100644 index 00000000..8d85af0a --- /dev/null +++ b/evidence/failures.txt @@ -0,0 +1 @@ +PASS private bucket, least privilege, bootstrap, S3 outage, aborted body diff --git a/evidence/final-local-checks.json b/evidence/final-local-checks.json new file mode 100644 index 00000000..c1ce30f7 --- /dev/null +++ b/evidence/final-local-checks.json @@ -0,0 +1,10 @@ +{ + "timestamp_utc": "2026-10-30T17:39:39.691788+00:00", + "public_contract_and_tests_unchanged": true, + "local_secret_scan": "no local secret values found in git-visible text files", + "full_integration_complete": true, + "integration_revalidation_required": false, + "checks_passed": 24, + "ten_successful_parallel_uploads_at_each_size": true, + "readiness_regressions_passed": 5 +} diff --git a/evidence/go-race.txt b/evidence/go-race.txt new file mode 100644 index 00000000..68e858fc --- /dev/null +++ b/evidence/go-race.txt @@ -0,0 +1,28 @@ +go: downloading github.com/minio/minio-go/v7 v7.4.1 +go: downloading golang.org/x/crypto v0.57.0 +go: downloading github.com/jackc/pgx/v5 v5.9.2 +go: downloading github.com/redis/go-redis/v9 v9.12.1 +go: downloading github.com/cespare/xxhash/v2 v2.3.0 +go: downloading github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f +go: downloading gopkg.in/ini.v1 v1.67.3 +go: downloading github.com/minio/md5-simd v1.1.2 +go: downloading golang.org/x/net v0.60.0 +go: downloading github.com/dustin/go-humanize v1.0.1 +go: downloading github.com/google/uuid v1.6.0 +go: downloading github.com/klauspost/compress v1.19.2 +go: downloading github.com/klauspost/crc32 v1.3.0 +go: downloading github.com/minio/crc64nvme v1.1.1 +go: downloading github.com/zeebo/xxh3 v1.1.0 +go: downloading go.yaml.in/yaml/v3 v3.0.5 +go: downloading github.com/jackc/puddle/v2 v2.2.2 +go: downloading github.com/jackc/pgpassfile v1.0.0 +go: downloading github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 +go: downloading golang.org/x/text v0.42.0 +go: downloading github.com/rs/xid v1.6.0 +go: downloading github.com/tinylib/msgp v1.6.4 +go: downloading github.com/klauspost/cpuid/v2 v2.4.0 +go: downloading golang.org/x/sys v0.48.0 +go: downloading golang.org/x/sync v0.23.0 +go: downloading github.com/philhofer/fwd v1.2.0 +ok mtusi-messenger 2.213s +? mtusi-messenger/infra [no test files] diff --git a/evidence/go-test.txt b/evidence/go-test.txt new file mode 100644 index 00000000..3481cf10 --- /dev/null +++ b/evidence/go-test.txt @@ -0,0 +1,2 @@ +ok mtusi-messenger (cached) +? mtusi-messenger/infra [no test files] diff --git a/evidence/go-vet.txt b/evidence/go-vet.txt new file mode 100644 index 00000000..e69de29b diff --git a/evidence/go-vuln.txt b/evidence/go-vuln.txt new file mode 100644 index 00000000..81b7034e --- /dev/null +++ b/evidence/go-vuln.txt @@ -0,0 +1,9 @@ +=== Symbol Results === + +No vulnerabilities found. + +Your code is affected by 0 vulnerabilities. +This scan also found 0 vulnerabilities in packages you import and 3 +vulnerabilities in modules you require, but your code doesn't appear to call +these vulnerabilities. +Use '-show verbose' for more details. diff --git a/evidence/infrastructure.json b/evidence/infrastructure.json new file mode 100644 index 00000000..f8011caa --- /dev/null +++ b/evidence/infrastructure.json @@ -0,0 +1,139 @@ +{ + "timestamp_utc": "2026-10-30T17:39:24.152775+00:00", + "containers": [ + { + "id": "bad03eba0f797ecf9b4533dc9a481928857468ec6b724f0df913a6a208f38d23", + "name": "/mtusi-lab4-api-1", + "instance": "bad03eba0f79", + "state": "running", + "started_at": "2026-10-30T17:36:32.095548483Z", + "nano_cpus": 1000000000, + "memory_bytes": 805306368, + "ports": { + "8080/tcp": null + }, + "image": "mtusi-messenger:lab4" + }, + { + "id": "7d3983584e28c15354b148f486a7cf6d688929bcf2fcd62d0208f02b4fa95eab", + "name": "/mtusi-lab4-api-2", + "instance": "7d3983584e28", + "state": "running", + "started_at": "2026-10-30T17:36:31.792326987Z", + "nano_cpus": 1000000000, + "memory_bytes": 805306368, + "ports": { + "8080/tcp": null + }, + "image": "mtusi-messenger:lab4" + }, + { + "id": "295ab00c9ff9868db00f419b13a6686790a185bd5d4fee2eb2d71af1b70d7894", + "name": "/mtusi-lab4-cleanup-1", + "instance": "295ab00c9ff9", + "state": "running", + "started_at": "2026-10-30T17:33:30.968955602Z", + "nano_cpus": 250000000, + "memory_bytes": 268435456, + "ports": { + "8080/tcp": null + }, + "image": "mtusi-messenger:lab4" + }, + { + "id": "c6b006c443fae052885f0713df55a0f0d023d8be356f5b0e2c4c16ad3d58f56a", + "name": "/mtusi-lab4-db-1", + "instance": "c6b006c443fa", + "state": "running", + "started_at": "2026-10-30T17:34:46.279164079Z", + "nano_cpus": 1000000000, + "memory_bytes": 536870912, + "ports": { + "5432/tcp": null + }, + "image": "postgres:17.6-bookworm@sha256:f3bd19c606e442c3d7bdfa8002e03fe260a1023351e0ea4598032022b68dd6e3" + }, + { + "id": "61d73bbbe53995b02b88c8bb12b14f62cb4f54d42a2dd78ce1b564552701ad8d", + "name": "/mtusi-lab4-lb-1", + "instance": "61d73bbbe539", + "state": "running", + "started_at": "2026-10-30T17:34:56.63772265Z", + "nano_cpus": 500000000, + "memory_bytes": 134217728, + "ports": { + "8080/tcp": [ + { + "HostIp": "127.0.0.1", + "HostPort": "8080" + } + ] + }, + "image": "haproxy:3.2.6-alpine" + }, + { + "id": "6a8a7e99597f3348befd363f2b02c20840a62c031be9cae0650d0b3f2363ab32", + "name": "/mtusi-lab4-migrate-1", + "instance": "6a8a7e99597f", + "state": "exited", + "started_at": "2026-10-30T17:33:23.966533767Z", + "nano_cpus": 500000000, + "memory_bytes": 268435456, + "ports": {}, + "image": "mtusi-messenger:lab4" + }, + { + "id": "72035d94e70ad3f996f34751c9533d7be313157a9001eb3df43e1e9a297ccaaf", + "name": "/mtusi-lab4-s3-1", + "instance": "72035d94e70a", + "state": "running", + "started_at": "2026-10-30T17:36:06.129926786Z", + "nano_cpus": 1000000000, + "memory_bytes": 1073741824, + "ports": {}, + "image": "mtusi-minio:RELEASE.2025-10-15T17-29-55Z" + }, + { + "id": "0516f33c5b0c1a7d2050f310663c4f5cf93d36f666220053aec0b28267a06e23", + "name": "/mtusi-lab4-s3-init-1", + "instance": "0516f33c5b0c", + "state": "exited", + "started_at": "2026-10-30T17:33:24.48278211Z", + "nano_cpus": 500000000, + "memory_bytes": 134217728, + "ports": {}, + "image": "mtusi-minio-tools:RELEASE.2025-08-13T08-35-41Z" + }, + { + "id": "96dc99b9811ca66a62e2917dbec82d101ce70d483715c50663c97aff7b032ae0", + "name": "/mtusi-lab4-valkey-1", + "instance": "96dc99b9811c", + "state": "running", + "started_at": "2026-10-30T17:34:46.422221358Z", + "nano_cpus": 500000000, + "memory_bytes": 268435456, + "ports": { + "6379/tcp": null + }, + "image": "valkey/valkey:8.1.3-bookworm@sha256:fea8b3e67b15729d4bb70589eb03367bab9ad1ee89c876f54327fc7c6e618571" + } + ], + "database": { + "users": 157, + "chats": 56, + "messages": 13055, + "idempotency_keys": 13055, + "database_bytes": 15453331, + "fsync": "on", + "synchronous_commit": "on", + "full_page_writes": "on" + }, + "docker_engine": { + "cpus": 12, + "memory_bytes": 3956068352, + "os_type": "linux", + "kernel": "6.18.54.1-microsoft-standard-WSL2", + "version": "29.3.0", + "operating_system": "Docker Desktop (containerized)" + } +} diff --git a/evidence/kdf-memory-diagnostic.json b/evidence/kdf-memory-diagnostic.json new file mode 100644 index 00000000..8c5340df --- /dev/null +++ b/evidence/kdf-memory-diagnostic.json @@ -0,0 +1,22 @@ +{ + "timestamp_utc": "2026-10-30T15:57:48.149130+00:00", + "method": "isolated synthetic Argon2id 64 MiB, t=3, p=1; 5 hashes with debug.FreeOSMemory after each; same image, 1 CPU, 768 MiB, no network", + "default_kdf_ms": [ + 708.618, + 1134.511, + 325.256, + 385.927, + 991.58 + ], + "madv_free_kdf_ms": [ + 505.942, + 154.841, + 220.599, + 170.899, + 186.14 + ], + "default_system_cpu_usec": 2820411, + "madv_free_system_cpu_usec": 356547, + "password_parameters_unchanged": true, + "limitation": "small diagnostic series; MADV_FREE retains RSS until memory pressure, so final ten-upload memory experiment is rerun" +} diff --git a/evidence/load.json b/evidence/load.json new file mode 100644 index 00000000..fece6dea --- /dev/null +++ b/evidence/load.json @@ -0,0 +1,17 @@ +{ + "lab": 4, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.069, + "concurrency": 4, + "successful_requests": 11543, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 383.878, + "successful_latency_ms": { + "p50": 7.953, + "p95": 27.216, + "p99": 34.457 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/load.txt b/evidence/load.txt new file mode 100644 index 00000000..fece6dea --- /dev/null +++ b/evidence/load.txt @@ -0,0 +1,17 @@ +{ + "lab": 4, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.069, + "concurrency": 4, + "successful_requests": 11543, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 383.878, + "successful_latency_ms": { + "p50": 7.953, + "p95": 27.216, + "p99": 34.457 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/memory-before-ipv4-fix.txt b/evidence/memory-before-ipv4-fix.txt new file mode 100644 index 00000000..3067faca --- /dev/null +++ b/evidence/memory-before-ipv4-fix.txt @@ -0,0 +1,10 @@ +Traceback (most recent call last): + File "C:\Users\maxsi\lab4\mtusi2026lab4-fork\student-tests\memory.py", line 89, in + main() + ~~~~^^ + File "C:\Users\maxsi\lab4\mtusi2026lab4-fork\student-tests\memory.py", line 34, in main + compose('up','-d','--no-deps','--force-recreate','--scale','api=2','api');wait_ready(count=2) + ~~~~~~~~~~^^^^^^^^^ + File "C:\Users\maxsi\lab4\mtusi2026lab4-fork\student-tests\common.py", line 63, in wait_ready + raise RuntimeError('stack did not become ready') +RuntimeError: stack did not become ready diff --git a/evidence/memory-readiness-diagnostic.json b/evidence/memory-readiness-diagnostic.json new file mode 100644 index 00000000..ed9e104b --- /dev/null +++ b/evidence/memory-readiness-diagnostic.json @@ -0,0 +1,33 @@ +{ + "timestamp_utc": "2026-10-30T17:39:38.317078+00:00", + "method": "TCP-only probes against the local Compose-published IPv4 loopback; no application data", + "localhost_resolution": [ + [ + 23, + "::1" + ], + [ + 2, + "127.0.0.1" + ] + ], + "tcp_probes": [ + { + "target": "::1", + "result": "ConnectionRefusedError", + "seconds": 2.064 + }, + { + "target": "127.0.0.1", + "result": "connected", + "seconds": 0.006 + }, + { + "target": "localhost", + "result": "connected", + "seconds": 2.09 + } + ], + "memory_cases_passed": 2, + "uploads_per_case": 10 +} diff --git a/evidence/memory.txt b/evidence/memory.txt new file mode 100644 index 00000000..9cf6b858 --- /dev/null +++ b/evidence/memory.txt @@ -0,0 +1 @@ +PASS 10-client memory experiment at two sizes (see upload-memory.json) diff --git a/evidence/minio-upstream-vulnerabilities.txt b/evidence/minio-upstream-vulnerabilities.txt new file mode 100644 index 00000000..5598785e --- /dev/null +++ b/evidence/minio-upstream-vulnerabilities.txt @@ -0,0 +1,793 @@ +=== Symbol Results === + +Vulnerability #1: GO-2026-6700 + Pre-negotiation frame limit is not enforced to 4KB in + github.com/rabbitmq/amqp091-go + More info: https://pkg.go.dev/vuln/GO-2026-6700 + Module: github.com/rabbitmq/amqp091-go + Found in: github.com/rabbitmq/amqp091-go@v1.10.0 + Fixed in: github.com/rabbitmq/amqp091-go@v1.14.0 + Vulnerable symbols found: + #1: amqp091.Dial + #2: amqp091.DialConfig + #3: amqp091.Open + +Vulnerability #2: GO-2026-6617 + HTTP/2 server crash due to HPACK encoder race in net/http + More info: https://pkg.go.dev/vuln/GO-2026-6617 + Module: golang.org/x/net + Found in: golang.org/x/net@v0.39.0 + Fixed in: golang.org/x/net@v0.60.0 + Vulnerable symbols found: + #1: http2.ClientConn.Close + #2: http2.ClientConn.Ping + #3: http2.ClientConn.RoundTrip + #4: http2.ClientConn.Shutdown + #5: http2.ConfigureTransports + Use '-show traces' to see the other 44 found symbols + +Vulnerability #3: GO-2026-6612 + Double flow control refund on HTTP/2 server streams in net/http + More info: https://pkg.go.dev/vuln/GO-2026-6612 + Module: golang.org/x/net + Found in: golang.org/x/net@v0.39.0 + Fixed in: golang.org/x/net@v0.60.0 + Vulnerable symbols found: + #1: http2.ClientConn.Close + #2: http2.ClientConn.Ping + #3: http2.ClientConn.RoundTrip + #4: http2.ClientConn.Shutdown + #5: http2.ConfigureTransports + Use '-show traces' to see the other 44 found symbols + +Vulnerability #4: GO-2026-6611 + Excessive CPU consumption from repeated initial window changes in net/http + More info: https://pkg.go.dev/vuln/GO-2026-6611 + Module: golang.org/x/net + Found in: golang.org/x/net@v0.39.0 + Fixed in: golang.org/x/net@v0.60.0 + Vulnerable symbols found: + #1: http2.ClientConn.Close + #2: http2.ClientConn.Ping + #3: http2.ClientConn.RoundTrip + #4: http2.ClientConn.Shutdown + #5: http2.ConfigureTransports + Use '-show traces' to see the other 44 found symbols + +Vulnerability #5: GO-2026-6610 + HTTP/2 transport accepts malformed framing-related headers in net/http + More info: https://pkg.go.dev/vuln/GO-2026-6610 + Module: golang.org/x/net + Found in: golang.org/x/net@v0.39.0 + Fixed in: golang.org/x/net@v0.60.0 + Vulnerable symbols found: + #1: http2.Transport.NewClientConn + #2: http2.Transport.RoundTrip + #3: http2.Transport.RoundTripOpt + #4: http2.clientConnPool.GetClientConn + #5: http2.noDialClientConnPool.GetClientConn + Use '-show traces' to see the other 3 found symbols + +Vulnerability #6: GO-2026-6603 + HTTP/2 server memory exhaustion due to Trailer headers in net/http + More info: https://pkg.go.dev/vuln/GO-2026-6603 + Module: golang.org/x/net + Found in: golang.org/x/net@v0.39.0 + Fixed in: golang.org/x/net@v0.60.0 + Vulnerable symbols found: + #1: http2.ClientConn.Close + #2: http2.ClientConn.Ping + #3: http2.ClientConn.RoundTrip + #4: http2.ClientConn.Shutdown + #5: http2.ConfigureTransports + Use '-show traces' to see the other 44 found symbols + +Vulnerability #7: GO-2026-6505 + OpenTelemetry-Go: Exporter config logging may leak endpoint URLs in info + logs in go.opentelemetry.io/otel/exporters/otlp/otlptrace + More info: https://pkg.go.dev/vuln/GO-2026-6505 + Module: go.opentelemetry.io/otel/sdk + Found in: go.opentelemetry.io/otel/sdk@v1.35.0 + Fixed in: go.opentelemetry.io/otel/sdk@v1.45.0 + Vulnerable symbols found: + #1: aggregate.Builder[float64].ExplicitBucketHistogram + #2: aggregate.Builder[float64].ExponentialBucketHistogram + #3: aggregate.Builder[float64].LastValue + #4: aggregate.Builder[float64].PrecomputedLastValue + #5: aggregate.Builder[float64].PrecomputedSum + Use '-show traces' to see the other 269 found symbols + + Module: go.opentelemetry.io/otel/sdk/metric + Found in: go.opentelemetry.io/otel/sdk/metric@v1.35.0 + Fixed in: N/A + Vulnerable symbols found: + #1: metricdata.Extrema[float64].MarshalJSON + #2: metricdata.Extrema[float64].MarshalText + #3: metricdata.Extrema[float64].Value + #4: metricdata.Extrema[float64].float64] + #5: metricdata.Extrema[float64].float64] + Use '-show traces' to see the other 16 found symbols + +Vulnerability #8: GO-2026-6503 + RabbitMQ amqp091-go: Denial of Service via Sub-Spec Frame Size Negotiation + in github.com/rabbitmq/amqp091-go + More info: https://pkg.go.dev/vuln/GO-2026-6503 + Module: github.com/rabbitmq/amqp091-go + Found in: github.com/rabbitmq/amqp091-go@v1.10.0 + Fixed in: github.com/rabbitmq/amqp091-go@v1.13.0 + Vulnerable symbols found: + #1: amqp091.Dial + #2: amqp091.DialConfig + #3: amqp091.Open + +Vulnerability #9: GO-2026-6502 + RabbitMQ amqp091-go: Consumer Message Flooding via Signed-to-Unsigned + Integer Casting in Qos Configuration in github.com/rabbitmq/amqp091-go + More info: https://pkg.go.dev/vuln/GO-2026-6502 + Module: github.com/rabbitmq/amqp091-go + Found in: github.com/rabbitmq/amqp091-go@v1.10.0 + Fixed in: github.com/rabbitmq/amqp091-go@v1.13.0 + Vulnerable symbols found: + #1: amqp091.Channel.Qos + +Vulnerability #10: GO-2026-6500 + RabbitMQ amqp091-go: Resource Exhaustion (OOM) via Unbounded Body Buffer + Allocation in github.com/rabbitmq/amqp091-go + More info: https://pkg.go.dev/vuln/GO-2026-6500 + Module: github.com/rabbitmq/amqp091-go + Found in: github.com/rabbitmq/amqp091-go@v1.10.0 + Fixed in: github.com/rabbitmq/amqp091-go@v1.13.0 + Vulnerable symbols found: + #1: amqp091.Dial + #2: amqp091.DialConfig + #3: amqp091.Open + +Vulnerability #11: GO-2026-6498 + RabbitMQ amqp091-go: Silent Data Truncation and State Corruption via + Shortstr Integer Overflow in github.com/rabbitmq/amqp091-go + More info: https://pkg.go.dev/vuln/GO-2026-6498 + Module: github.com/rabbitmq/amqp091-go + Found in: github.com/rabbitmq/amqp091-go@v1.10.0 + Fixed in: github.com/rabbitmq/amqp091-go@v1.13.0 + Vulnerable symbols found: + #1: amqp091.AMQPlainAuth.Response + #2: amqp091.Channel.Ack + #3: amqp091.Channel.Cancel + #4: amqp091.Channel.Close + #5: amqp091.Channel.Confirm + Use '-show traces' to see the other 39 found symbols + +Vulnerability #12: GO-2026-6496 + RabbitMQ amqp091-go: Protocol Desynchronization and Frame Injection via + Integer Overflow in readLongstr in github.com/rabbitmq/amqp091-go + More info: https://pkg.go.dev/vuln/GO-2026-6496 + Module: github.com/rabbitmq/amqp091-go + Found in: github.com/rabbitmq/amqp091-go@v1.10.0 + Fixed in: github.com/rabbitmq/amqp091-go@v1.13.0 + Vulnerable symbols found: + #1: amqp091.Dial + #2: amqp091.DialConfig + #3: amqp091.Open + #4: amqp091.reader.ReadFrame + +Vulnerability #13: GO-2026-6494 + RabbitMQ amqp091-go: Denial of Service via Malicious Field Length in AMQP + Client in github.com/rabbitmq/amqp091-go + More info: https://pkg.go.dev/vuln/GO-2026-6494 + Module: github.com/rabbitmq/amqp091-go + Found in: github.com/rabbitmq/amqp091-go@v1.10.0 + Fixed in: github.com/rabbitmq/amqp091-go@v1.13.0 + Vulnerable symbols found: + #1: amqp091.Dial + #2: amqp091.DialConfig + #3: amqp091.Open + #4: amqp091.reader.ReadFrame + +Vulnerability #14: GO-2026-6493 + RabbitMQ amqp091-go: Connection Configuration Overwrite via Unsanitized TLS + Path Parameter Injection in github.com/rabbitmq/amqp091-go + More info: https://pkg.go.dev/vuln/GO-2026-6493 + Module: github.com/rabbitmq/amqp091-go + Found in: github.com/rabbitmq/amqp091-go@v1.10.0 + Fixed in: github.com/rabbitmq/amqp091-go@v1.13.0 + Vulnerable symbols found: + #1: amqp091.URI.String + +Vulnerability #15: GO-2026-6492 + RabbitMQ amqp091-go: Missing Explicit TLS Minimum Version Configuration In + URI Parser in github.com/rabbitmq/amqp091-go + More info: https://pkg.go.dev/vuln/GO-2026-6492 + Module: github.com/rabbitmq/amqp091-go + Found in: github.com/rabbitmq/amqp091-go@v1.10.0 + Fixed in: github.com/rabbitmq/amqp091-go@v1.13.0 + Vulnerable symbols found: + #1: amqp091.Dial + #2: amqp091.DialConfig + +Vulnerability #16: GO-2026-6491 + RabbitMQ amqp091-go: Plaintext Credential Exposure via Exported PLAIN + Authentication Struct Fields in github.com/rabbitmq/amqp091-go + More info: https://pkg.go.dev/vuln/GO-2026-6491 + Module: github.com/rabbitmq/amqp091-go + Found in: github.com/rabbitmq/amqp091-go@v1.10.0 + Fixed in: github.com/rabbitmq/amqp091-go@v1.13.0 + Vulnerable symbols found: + #1: amqp091.Dial + #2: amqp091.DialConfig + #3: amqp091.Open + +Vulnerability #17: GO-2026-6443 + Server panic via missing authority or Host headers in google.golang.org/grpc + More info: https://pkg.go.dev/vuln/GO-2026-6443 + Module: google.golang.org/grpc + Found in: google.golang.org/grpc@v1.72.0 + Fixed in: google.golang.org/grpc@v1.82.2 + Vulnerable symbols found: + #1: transport.http2Server.HandleStreams + +Vulnerability #18: GO-2026-6372 + Potential Memory Exhaustion/Protocol Violation via Broker-Controlled + Oversized Payload in github.com/rabbitmq/amqp091-go + More info: https://pkg.go.dev/vuln/GO-2026-6372 + Module: github.com/rabbitmq/amqp091-go + Found in: github.com/rabbitmq/amqp091-go@v1.10.0 + Fixed in: github.com/rabbitmq/amqp091-go@v1.13.0 + Vulnerable symbols found: + #1: amqp091.AMQPlainAuth.Mechanism + #2: amqp091.AMQPlainAuth.Response + #3: amqp091.Channel.Ack + #4: amqp091.Channel.Cancel + #5: amqp091.Channel.Close + Use '-show traces' to see the other 89 found symbols + +Vulnerability #19: GO-2026-6355 + Prevent DoS on deadlocked established channel in golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-6355 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.56.0 + Vulnerable symbols found: + #1: ssh.NewServerConn + +Vulnerability #20: GO-2026-6354 + Prevent DoS on deadlocked undecided channel in golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-6354 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.56.0 + Vulnerable symbols found: + #1: ssh.NewServerConn + #2: ssh.channel.Accept + +Vulnerability #21: GO-2026-6348 + Heap Memory Exhaustion (OOM) via HTTP/2 DATA Frame Fragmentation in + google.golang.org/grpc + More info: https://pkg.go.dev/vuln/GO-2026-6348 + Module: google.golang.org/grpc + Found in: google.golang.org/grpc@v1.72.0 + Fixed in: google.golang.org/grpc@v1.83.1 + Vulnerable symbols found: + #1: mem.BufferSlice.MaterializeToBuffer + #2: mem.Copy + #3: mem.IsBelowBufferPoolingThreshold + #4: mem.NewBuffer + #5: mem.ReadAll + Use '-show traces' to see the other 20 found symbols + +Vulnerability #22: GO-2026-6303 + Source-address critical option not enforced for non-public-key auth + callbacks in golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-6303 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.55.0 + Vulnerable symbols found: + #1: ssh.NewServerConn + +Vulnerability #23: GO-2026-6061 + Vulnerabilities in the xDS RBAC authorization engine and the HTTP/2 + transport server implementation in google.golang.org/grpc + More info: https://pkg.go.dev/vuln/GO-2026-6061 + Module: google.golang.org/grpc + Found in: google.golang.org/grpc@v1.72.0 + Fixed in: google.golang.org/grpc@v1.82.1 + Vulnerable symbols found: + #1: rbac.ChainEngine.IsAuthorized + #2: rbac.NewChainEngine + #3: transport.ClientStream.Close + #4: transport.ClientStream.Header + #5: transport.ClientStream.Read + Use '-show traces' to see the other 19 found symbols + +Vulnerability #24: GO-2026-5970 + Infinite loop on invalid input in golang.org/x/text + More info: https://pkg.go.dev/vuln/GO-2026-5970 + Module: golang.org/x/text + Found in: golang.org/x/text@v0.24.0 + Fixed in: golang.org/x/text@v0.39.0 + Vulnerable symbols found: + #1: norm.Form.String + +Vulnerability #25: GO-2026-5757 + MinIO vulnerable to Path Traversal via msgpack Body in `ReadMultiple` + Storage-REST Endpoint in github.com/minio/minio + More info: https://pkg.go.dev/vuln/GO-2026-5757 + Module: github.com/minio/minio + Found in: github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648 + Fixed in: N/A + Vulnerable symbols found: + #1: amztime.ISO8601Format + #2: amztime.ISO8601Parse + #3: amztime.Parse + #4: amztime.ParseHeader + #5: amztime.ParseReplicationTS + Use '-show traces' to see the other 6116 found symbols + + Module: github.com/minio/minio-go/v7 + Found in: github.com/minio/minio-go/v7@v7.0.91 + Fixed in: N/A + Vulnerable symbols found: + #1: cors.Config.ToXML + #2: cors.ParseBucketCorsConfig + #3: credentials.Chain.IsExpired + #4: credentials.Chain.Retrieve + #5: credentials.Chain.RetrieveWithCredContext + Use '-show traces' to see the other 601 found symbols + +Vulnerability #26: GO-2026-5710 + Prometheus Azure AD remote write OAuth client secret exposed via config API + in github.com/prometheus/prometheus + More info: https://pkg.go.dev/vuln/GO-2026-5710 + Module: github.com/prometheus/prometheus + Found in: github.com/prometheus/prometheus@v0.303.0 + Fixed in: github.com/prometheus/prometheus@v0.311.3 + Vulnerable symbols found: + #1: histogram.Bucket[float64].String + #2: histogram.Bucket[float64].float64] + #3: histogram.Bucket[go.shape + #4: histogram.Bucket[go.shape + #5: histogram.Bucket[uint64].String + Use '-show traces' to see the other 19 found symbols + +Vulnerability #27: GO-2026-5662 + Prometheus has Stored XSS via metric names and label values in Prometheus + web UI in github.com/prometheus/prometheus + More info: https://pkg.go.dev/vuln/GO-2026-5662 + Module: github.com/prometheus/prometheus + Found in: github.com/prometheus/prometheus@v0.303.0 + Fixed in: github.com/prometheus/prometheus@v0.311.2-0.20260410083055-07c6232d159b + Vulnerable symbols found: + #1: histogram.Bucket[float64].String + #2: histogram.Bucket[float64].float64] + #3: histogram.Bucket[go.shape + #4: histogram.Bucket[go.shape + #5: histogram.Bucket[uint64].String + Use '-show traces' to see the other 19 found symbols + +Vulnerability #28: GO-2026-5437 + MinIO has an Unauthenticated Object Write via Query-String Credential + Signature Bypass in Unsigned-Trailer Uploads in github.com/minio/minio + More info: https://pkg.go.dev/vuln/GO-2026-5437 + Module: github.com/minio/minio + Found in: github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648 + Fixed in: N/A + Vulnerable symbols found: + #1: amztime.ISO8601Format + #2: amztime.ISO8601Parse + #3: amztime.Parse + #4: amztime.ParseHeader + #5: amztime.ParseReplicationTS + Use '-show traces' to see the other 6116 found symbols + + Module: github.com/minio/minio-go/v7 + Found in: github.com/minio/minio-go/v7@v7.0.91 + Fixed in: N/A + Vulnerable symbols found: + #1: cors.Config.ToXML + #2: cors.ParseBucketCorsConfig + #3: credentials.Chain.IsExpired + #4: credentials.Chain.Retrieve + #5: credentials.Chain.RetrieveWithCredContext + Use '-show traces' to see the other 601 found symbols + +Vulnerability #29: GO-2026-5415 + MinIO affected a DoS via Unbounded Memory Allocation in S3 Select CSV + Parsing in github.com/minio/minio + More info: https://pkg.go.dev/vuln/GO-2026-5415 + Module: github.com/minio/minio + Found in: github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648 + Fixed in: N/A + Vulnerable symbols found: + #1: amztime.ISO8601Format + #2: amztime.ISO8601Parse + #3: amztime.Parse + #4: amztime.ParseHeader + #5: amztime.ParseReplicationTS + Use '-show traces' to see the other 6116 found symbols + + Module: github.com/minio/minio-go/v7 + Found in: github.com/minio/minio-go/v7@v7.0.91 + Fixed in: N/A + Vulnerable symbols found: + #1: cors.Config.ToXML + #2: cors.ParseBucketCorsConfig + #3: credentials.Chain.IsExpired + #4: credentials.Chain.Retrieve + #5: credentials.Chain.RetrieveWithCredContext + Use '-show traces' to see the other 601 found symbols + +Vulnerability #30: GO-2026-5381 + Prometheus vulnerable to stored XSS via crafted histogram bucket label + values in the old web UI heatmap display in github.com/prometheus/prometheus + More info: https://pkg.go.dev/vuln/GO-2026-5381 + Module: github.com/prometheus/prometheus + Found in: github.com/prometheus/prometheus@v0.303.0 + Fixed in: github.com/prometheus/prometheus@v0.311.3 + Vulnerable symbols found: + #1: histogram.Bucket[float64].String + #2: histogram.Bucket[float64].float64] + #3: histogram.Bucket[go.shape + #4: histogram.Bucket[go.shape + #5: histogram.Bucket[uint64].String + Use '-show traces' to see the other 19 found symbols + +Vulnerability #31: GO-2026-5284 + MinIO has an Unauthenticated Object Write via Missing Signature Verification + in Unsigned-Trailer Uploads in github.com/minio/minio + More info: https://pkg.go.dev/vuln/GO-2026-5284 + Module: github.com/minio/minio + Found in: github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648 + Fixed in: N/A + Vulnerable symbols found: + #1: amztime.ISO8601Format + #2: amztime.ISO8601Parse + #3: amztime.Parse + #4: amztime.ParseHeader + #5: amztime.ParseReplicationTS + Use '-show traces' to see the other 6116 found symbols + + Module: github.com/minio/minio-go/v7 + Found in: github.com/minio/minio-go/v7@v7.0.91 + Fixed in: N/A + Vulnerable symbols found: + #1: cors.Config.ToXML + #2: cors.ParseBucketCorsConfig + #3: credentials.Chain.IsExpired + #4: credentials.Chain.Retrieve + #5: credentials.Chain.RetrieveWithCredContext + Use '-show traces' to see the other 601 found symbols + +Vulnerability #32: GO-2026-5264 + Prometheus: Remote read endpoint allows denial of service via crafted snappy + payload in github.com/prometheus/prometheus + More info: https://pkg.go.dev/vuln/GO-2026-5264 + Module: github.com/prometheus/prometheus + Found in: github.com/prometheus/prometheus@v0.303.0 + Fixed in: github.com/prometheus/prometheus@v0.305.2 + Vulnerable symbols found: + #1: histogram.Bucket[float64].String + #2: histogram.Bucket[float64].float64] + #3: histogram.Bucket[go.shape + #4: histogram.Bucket[go.shape + #5: histogram.Bucket[uint64].String + Use '-show traces' to see the other 19 found symbols + +Vulnerability #33: GO-2026-5026 + Invoking failure to reject ASCII-only Punycode-encoded labels in + golang.org/x/net/idna + More info: https://pkg.go.dev/vuln/GO-2026-5026 + Module: golang.org/x/net + Found in: golang.org/x/net@v0.39.0 + Fixed in: golang.org/x/net@v0.55.0 + Vulnerable symbols found: + #1: idna.ToASCII + +Vulnerability #34: GO-2026-5023 + Invoking VerifiedPublicKeyCallback permissions skip enforcement in + golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-5023 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.52.0 + Vulnerable symbols found: + #1: ssh.NewServerConn + +Vulnerability #35: GO-2026-5020 + Invoking infinite loop on large channel writes in golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-5020 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.52.0 + Vulnerable symbols found: + #1: ssh.NewServerConn + #2: ssh.channel.Write + #3: ssh.channel.WriteExtended + #4: ssh.curve25519sha256.Client + #5: ssh.curve25519sha256.Server + Use '-show traces' to see the other 7 found symbols + +Vulnerability #36: GO-2026-5019 + Invoking bypass of FIDO/U2F security keys physical interaction in + golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-5019 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.52.0 + Vulnerable symbols found: + #1: ssh.CertChecker.Authenticate + #2: ssh.CertChecker.CheckCert + #3: ssh.Certificate.Verify + #4: ssh.NewServerConn + #5: ssh.skECDSAPublicKey.Verify + Use '-show traces' to see the other 1 found symbols + +Vulnerability #37: GO-2026-5018 + Invoking pathological RSA/DSA parameters may cause DoS in + golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-5018 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.52.0 + Vulnerable symbols found: + #1: ssh.NewServerConn + #2: ssh.NewSignerFromKey + #3: ssh.ParseAuthorizedKey + #4: ssh.ParsePrivateKey + #5: ssh.ParsePublicKey + Use '-show traces' to see the other 1 found symbols + +Vulnerability #38: GO-2026-5017 + Invoking client can cause server deadlock on unexpected responses in + golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-5017 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.52.0 + Vulnerable symbols found: + #1: ssh.NewServerConn + #2: ssh.channel.SendRequest + #3: ssh.mux.SendRequest + +Vulnerability #39: GO-2026-5016 + Invoking memory leak when rejecting channels can lead to DoS in + golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-5016 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.52.0 + Vulnerable symbols found: + #1: ssh.channel.Reject + +Vulnerability #40: GO-2026-5015 + Invoking server panic during CheckHostKey/Authenticate in + golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-5015 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.52.0 + Vulnerable symbols found: + #1: ssh.CertChecker.Authenticate + +Vulnerability #41: GO-2026-5014 + Invoking bypass of certificate restrictions in golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-5014 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.52.0 + Vulnerable symbols found: + #1: ssh.NewServerConn + +Vulnerability #42: GO-2026-5013 + Invoking byte arithmetic causes underflow and panic in + golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2026-5013 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.52.0 + Vulnerable symbols found: + #1: ssh.NewServerConn + #2: ssh.curve25519sha256.Client + #3: ssh.curve25519sha256.Server + #4: ssh.dhGEXSHA.Client + #5: ssh.dhGEXSHA.Server + Use '-show traces' to see the other 4 found symbols + +Vulnerability #43: GO-2026-4945 + Go JOSE Panics in JWE decryption in github.com/go-jose/go-jose + More info: https://pkg.go.dev/vuln/GO-2026-4945 + Module: github.com/go-jose/go-jose/v4 + Found in: github.com/go-jose/go-jose/v4@v4.1.0 + Fixed in: github.com/go-jose/go-jose/v4@v4.1.4 + Vulnerable symbols found: + #1: jose.JSONWebKey.IsPublic + #2: jose.JSONWebKey.MarshalJSON + #3: jose.JSONWebKey.Public + #4: jose.JSONWebKey.Thumbprint + #5: jose.JSONWebKey.UnmarshalJSON + Use '-show traces' to see the other 4 found symbols + +Vulnerability #44: GO-2026-4918 + Infinite loop in HTTP/2 transport when given bad SETTINGS_MAX_FRAME_SIZE in + net/http/internal/http2 in golang.org/x/net + More info: https://pkg.go.dev/vuln/GO-2026-4918 + Module: golang.org/x/net + Found in: golang.org/x/net@v0.39.0 + Fixed in: golang.org/x/net@v0.53.0 + Vulnerable symbols found: + #1: http2.Transport.NewClientConn + #2: http2.Transport.RoundTrip + #3: http2.Transport.RoundTripOpt + #4: http2.clientConnPool.GetClientConn + #5: http2.noDialClientConnPool.GetClientConn + Use '-show traces' to see the other 3 found symbols + +Vulnerability #45: GO-2026-4896 + MinIO is Vulnerable to SSE Metadata Injection via Replication Headers in + github.com/minio/minio + More info: https://pkg.go.dev/vuln/GO-2026-4896 + Module: github.com/minio/minio + Found in: github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648 + Fixed in: N/A + Vulnerable symbols found: + #1: amztime.ISO8601Format + #2: amztime.ISO8601Parse + #3: amztime.Parse + #4: amztime.ParseHeader + #5: amztime.ParseReplicationTS + Use '-show traces' to see the other 6116 found symbols + + Module: github.com/minio/minio-go/v7 + Found in: github.com/minio/minio-go/v7@v7.0.91 + Fixed in: N/A + Vulnerable symbols found: + #1: cors.Config.ToXML + #2: cors.ParseBucketCorsConfig + #3: credentials.Chain.IsExpired + #4: credentials.Chain.Retrieve + #5: credentials.Chain.RetrieveWithCredContext + Use '-show traces' to see the other 601 found symbols + +Vulnerability #46: GO-2026-4803 + MinIO LDAP login brute-force via user enumeration and missing rate limit in + github.com/minio/minio + More info: https://pkg.go.dev/vuln/GO-2026-4803 + Module: github.com/minio/minio + Found in: github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648 + Fixed in: N/A + Vulnerable symbols found: + #1: amztime.ISO8601Format + #2: amztime.ISO8601Parse + #3: amztime.Parse + #4: amztime.ParseHeader + #5: amztime.ParseReplicationTS + Use '-show traces' to see the other 6116 found symbols + + Module: github.com/minio/minio-go/v7 + Found in: github.com/minio/minio-go/v7@v7.0.91 + Fixed in: N/A + Vulnerable symbols found: + #1: cors.Config.ToXML + #2: cors.ParseBucketCorsConfig + #3: credentials.Chain.IsExpired + #4: credentials.Chain.Retrieve + #5: credentials.Chain.RetrieveWithCredContext + Use '-show traces' to see the other 601 found symbols + +Vulnerability #47: GO-2026-4779 + MinIO has JWT Algorithm Confusion in OIDC Authentication in + github.com/minio/minio + More info: https://pkg.go.dev/vuln/GO-2026-4779 + Module: github.com/minio/minio + Found in: github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648 + Fixed in: N/A + Vulnerable symbols found: + #1: amztime.ISO8601Format + #2: amztime.ISO8601Parse + #3: amztime.Parse + #4: amztime.ParseHeader + #5: amztime.ParseReplicationTS + Use '-show traces' to see the other 6116 found symbols + + Module: github.com/minio/minio-go/v7 + Found in: github.com/minio/minio-go/v7@v7.0.91 + Fixed in: N/A + Vulnerable symbols found: + #1: cors.Config.ToXML + #2: cors.ParseBucketCorsConfig + #3: credentials.Chain.IsExpired + #4: credentials.Chain.Retrieve + #5: credentials.Chain.RetrieveWithCredContext + Use '-show traces' to see the other 601 found symbols + +Vulnerability #48: GO-2026-4762 + Authorization bypass in gRPC-Go via missing leading slash in :path in + google.golang.org/grpc + More info: https://pkg.go.dev/vuln/GO-2026-4762 + Module: google.golang.org/grpc + Found in: google.golang.org/grpc@v1.72.0 + Fixed in: google.golang.org/grpc@v1.79.3 + Vulnerable symbols found: + #1: grpc.Server.Serve + #2: grpc.Server.ServeHTTP + +Vulnerability #49: GO-2026-4394 + OpenTelemetry Go SDK Vulnerable to Arbitrary Code Execution via PATH + Hijacking in go.opentelemetry.io/otel/sdk + More info: https://pkg.go.dev/vuln/GO-2026-4394 + Module: go.opentelemetry.io/otel/sdk + Found in: go.opentelemetry.io/otel/sdk@v1.35.0 + Fixed in: go.opentelemetry.io/otel/sdk@v1.40.0 + Vulnerable symbols found: + #1: aggregate.Builder[float64].ExplicitBucketHistogram + #2: aggregate.Builder[float64].ExponentialBucketHistogram + #3: aggregate.Builder[float64].LastValue + #4: aggregate.Builder[float64].PrecomputedLastValue + #5: aggregate.Builder[float64].PrecomputedSum + Use '-show traces' to see the other 269 found symbols + + Module: go.opentelemetry.io/otel/sdk/metric + Found in: go.opentelemetry.io/otel/sdk/metric@v1.35.0 + Fixed in: N/A + Vulnerable symbols found: + #1: metricdata.Extrema[float64].MarshalJSON + #2: metricdata.Extrema[float64].MarshalText + #3: metricdata.Extrema[float64].Value + #4: metricdata.Extrema[float64].float64] + #5: metricdata.Extrema[float64].float64] + Use '-show traces' to see the other 16 found symbols + +Vulnerability #50: GO-2025-4173 + Eclipse Paho Go MQTT may incorrectly encode strings if length exceeds 65535 + bytes in github.com/eclipse/paho.mqtt.golang + More info: https://pkg.go.dev/vuln/GO-2025-4173 + Module: github.com/eclipse/paho.mqtt.golang + Found in: github.com/eclipse/paho.mqtt.golang@v1.5.0 + Fixed in: github.com/eclipse/paho.mqtt.golang@v1.5.1 + Vulnerable symbols found: + #1: packets.ConnackPacket.Details + #2: packets.ConnackPacket.String + #3: packets.ConnackPacket.Unpack + #4: packets.ConnackPacket.Write + #5: packets.ConnectPacket.Details + Use '-show traces' to see the other 247 found symbols + +Vulnerability #51: GO-2025-4134 + Unbounded memory consumption in golang.org/x/crypto/ssh + More info: https://pkg.go.dev/vuln/GO-2025-4134 + Module: golang.org/x/crypto + Found in: golang.org/x/crypto@v0.37.0 + Fixed in: golang.org/x/crypto@v0.45.0 + Vulnerable symbols found: + #1: ssh.NewServerConn + +Vulnerability #52: GO-2025-3495 + MinIO SFTP authentication bypass due to improperly trusted SSH key in + github.com/minio/minio + More info: https://pkg.go.dev/vuln/GO-2025-3495 + Module: github.com/minio/minio + Found in: github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648 + Fixed in: N/A + Vulnerable symbols found: + #1: amztime.ISO8601Format + #2: amztime.ISO8601Parse + #3: amztime.Parse + #4: amztime.ParseHeader + #5: amztime.ParseReplicationTS + Use '-show traces' to see the other 6116 found symbols + + Module: github.com/minio/minio-go/v7 + Found in: github.com/minio/minio-go/v7@v7.0.91 + Fixed in: N/A + Vulnerable symbols found: + #1: cors.Config.ToXML + #2: cors.ParseBucketCorsConfig + #3: credentials.Chain.IsExpired + #4: credentials.Chain.Retrieve + #5: credentials.Chain.RetrieveWithCredContext + Use '-show traces' to see the other 601 found symbols + +Your code is affected by 52 vulnerabilities from 10 modules. +This scan also found 4 vulnerabilities in packages you import and 22 +vulnerabilities in modules you require, but your code doesn't appear to call +these vulnerabilities. +Use '-show verbose' for more details. diff --git a/evidence/openapi.txt b/evidence/openapi.txt new file mode 100644 index 00000000..683be253 --- /dev/null +++ b/evidence/openapi.txt @@ -0,0 +1,2 @@ +python3 scripts/validate_openapi.py +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..bf693b5d --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://lb:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/protected-files.json b/evidence/protected-files.json new file mode 100644 index 00000000..e267e850 --- /dev/null +++ b/evidence/protected-files.json @@ -0,0 +1,14 @@ +{ + "contracts/examples.json": "2816da2e63058d55bdcbeceb92b231ea2509c86df8c5a0aa908be83bd0599469", + "contracts/infrastructure.json": "18a6b38deab39878da174f01e54addc4c7de556f9b3b7f37d96ec1ef0dd240b7", + "contracts/openapi.json": "61c7dbac7bd8d57423a2883b4b7b1277e8e35918d25c37e2cd02eaf6817936f0", + "contracts/README.md": "4c04faede4a2ffa35183455b51da21764b7fa3997c0a4b3963614b82586eed28", + "tests/client.py": "b318084e2a4c380db91a55d082190bf33979fa556a4c4ca87e01f46ae275775c", + "tests/image_probe.py": "ef48d8882ab138b9699a173e7419e5814c22a10b01b6b0ddbb50ea49481a5baa", + "tests/load.py": "9a9aff05e109630e243c3b092d7bd564344e4872b29e38b6618647a08460a72e", + "tests/README.md": "89afb3063ec0ccd7cb68fdac1de57513f9cc81b77bad96f202daaca2b66a5e82", + "tests/resilience.py": "4ba30b9c81a0664127ddab2b0bea5e76aa2087be8bb25aa13cd5a8e69be23fdd", + "tests/smoke.py": "354e168e1e644145c3ff50bbbe189fd217cce5659aa125f588098025ffab0fdf", + "tests/fixtures/README.md": "0eaa4e8837032d1786fc0c4b1576656ff3f4d1931fdd51b80e5c053f88ab3872", + "tests/fixtures/sample.png": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75" +} \ No newline at end of file diff --git a/evidence/ready-before-failover.txt b/evidence/ready-before-failover.txt new file mode 100644 index 00000000..479e931f --- /dev/null +++ b/evidence/ready-before-failover.txt @@ -0,0 +1,8 @@ + Container mtusi-lab4-api-1 Recreate + Container mtusi-lab4-api-2 Recreate + Container mtusi-lab4-api-2 Recreated + Container mtusi-lab4-api-1 Recreated + Container mtusi-lab4-api-1 Starting + Container mtusi-lab4-api-1 Started + Container mtusi-lab4-api-2 Starting + Container mtusi-lab4-api-2 Started diff --git a/evidence/research.json b/evidence/research.json new file mode 100644 index 00000000..fea291df --- /dev/null +++ b/evidence/research.json @@ -0,0 +1,276 @@ +{ + "complete": true, + "track": 2, + "grace_seconds": 60, + "hypothesis": "Per-key locks, durable PostgreSQL rechecks and age threshold remove only old unreferenced objects; missing metadata is retained and recoverable.", + "faults": [ + "PostgreSQL INSERT exception after successful S3 PUT", + "S3 object removed after acknowledged upload" + ], + "dry_run": { + "apply": false, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:03.164108Z", + "objects_scanned": 131, + "metadata_scanned": 130, + "old_orphans": 1, + "fresh_protected": 1, + "metadata_protected": 129, + "active_protected": 0, + "missing": 1, + "recovered": 0, + "deleted": 0, + "marked_unavailable": 0, + "cleared_unavailable": 0, + "head_requests": 132, + "get_requests": 0, + "verified_bytes": 0, + "elapsed_ms": 323, + "complete": true + }, + "apply": { + "apply": true, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:06.027858Z", + "objects_scanned": 131, + "metadata_scanned": 130, + "old_orphans": 1, + "fresh_protected": 1, + "metadata_protected": 129, + "active_protected": 0, + "missing": 1, + "recovered": 0, + "deleted": 1, + "marked_unavailable": 1, + "cleared_unavailable": 0, + "head_requests": 132, + "get_requests": 0, + "verified_bytes": 0, + "elapsed_ms": 429, + "complete": true + }, + "repeat_apply": { + "apply": true, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:09.830275Z", + "objects_scanned": 130, + "metadata_scanned": 130, + "old_orphans": 0, + "fresh_protected": 1, + "metadata_protected": 129, + "active_protected": 0, + "missing": 1, + "recovered": 0, + "deleted": 0, + "marked_unavailable": 0, + "cleared_unavailable": 0, + "head_requests": 131, + "get_requests": 0, + "verified_bytes": 0, + "elapsed_ms": 547, + "complete": true + }, + "recovery": { + "apply": true, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:12.350328Z", + "objects_scanned": 131, + "metadata_scanned": 130, + "old_orphans": 0, + "fresh_protected": 1, + "metadata_protected": 130, + "active_protected": 0, + "missing": 0, + "recovered": 1, + "deleted": 0, + "marked_unavailable": 0, + "cleared_unavailable": 1, + "head_requests": 131, + "get_requests": 1, + "verified_bytes": 111817, + "elapsed_ms": 495, + "complete": true + }, + "concurrent": { + "apply": true, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:13.500580Z", + "objects_scanned": 134, + "metadata_scanned": 133, + "old_orphans": 0, + "fresh_protected": 4, + "metadata_protected": 133, + "active_protected": 0, + "missing": 0, + "recovered": 0, + "deleted": 0, + "marked_unavailable": 0, + "cleared_unavailable": 0, + "head_requests": 131, + "get_requests": 0, + "verified_bytes": 0, + "elapsed_ms": 426, + "complete": true + }, + "fresh_orphan_protected": true, + "used_original_checksum": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75", + "scan_cost": [ + { + "added_objects": 10, + "runs": [ + { + "apply": false, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:18.155529Z", + "objects_scanned": 144, + "metadata_scanned": 133, + "old_orphans": 0, + "fresh_protected": 14, + "metadata_protected": 133, + "active_protected": 0, + "missing": 0, + "recovered": 0, + "deleted": 0, + "marked_unavailable": 0, + "cleared_unavailable": 0, + "head_requests": 141, + "get_requests": 0, + "verified_bytes": 0, + "elapsed_ms": 629, + "complete": true + }, + { + "apply": false, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:19.349362Z", + "objects_scanned": 144, + "metadata_scanned": 133, + "old_orphans": 0, + "fresh_protected": 14, + "metadata_protected": 133, + "active_protected": 0, + "missing": 0, + "recovered": 0, + "deleted": 0, + "marked_unavailable": 0, + "cleared_unavailable": 0, + "head_requests": 141, + "get_requests": 0, + "verified_bytes": 0, + "elapsed_ms": 454, + "complete": true + }, + { + "apply": false, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:20.376076Z", + "objects_scanned": 144, + "metadata_scanned": 133, + "old_orphans": 0, + "fresh_protected": 14, + "metadata_protected": 133, + "active_protected": 0, + "missing": 0, + "recovered": 0, + "deleted": 0, + "marked_unavailable": 0, + "cleared_unavailable": 0, + "head_requests": 141, + "get_requests": 0, + "verified_bytes": 0, + "elapsed_ms": 269, + "complete": true + } + ] + }, + { + "added_objects": 100, + "runs": [ + { + "apply": false, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:39.331089Z", + "objects_scanned": 244, + "metadata_scanned": 133, + "old_orphans": 0, + "fresh_protected": 114, + "metadata_protected": 133, + "active_protected": 0, + "missing": 0, + "recovered": 0, + "deleted": 0, + "marked_unavailable": 0, + "cleared_unavailable": 0, + "head_requests": 241, + "get_requests": 0, + "verified_bytes": 0, + "elapsed_ms": 615, + "complete": true + }, + { + "apply": false, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:40.446324Z", + "objects_scanned": 244, + "metadata_scanned": 133, + "old_orphans": 0, + "fresh_protected": 114, + "metadata_protected": 133, + "active_protected": 0, + "missing": 0, + "recovered": 0, + "deleted": 0, + "marked_unavailable": 0, + "cleared_unavailable": 0, + "head_requests": 241, + "get_requests": 0, + "verified_bytes": 0, + "elapsed_ms": 554, + "complete": true + }, + { + "apply": false, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:41.602835Z", + "objects_scanned": 244, + "metadata_scanned": 133, + "old_orphans": 0, + "fresh_protected": 114, + "metadata_protected": 133, + "active_protected": 0, + "missing": 0, + "recovered": 0, + "deleted": 0, + "marked_unavailable": 0, + "cleared_unavailable": 0, + "head_requests": 241, + "get_requests": 0, + "verified_bytes": 0, + "elapsed_ms": 487, + "complete": true + } + ] + } + ], + "final": { + "apply": false, + "grace_seconds": 60, + "cutoff": "2026-10-30T17:37:42.591332Z", + "objects_scanned": 244, + "metadata_scanned": 133, + "old_orphans": 0, + "fresh_protected": 114, + "metadata_protected": 133, + "active_protected": 0, + "missing": 0, + "recovered": 0, + "deleted": 0, + "marked_unavailable": 0, + "cleared_unavailable": 0, + "head_requests": 241, + "get_requests": 0, + "verified_bytes": 0, + "elapsed_ms": 482, + "complete": true + } +} diff --git a/evidence/research.txt b/evidence/research.txt new file mode 100644 index 00000000..78e9a66c --- /dev/null +++ b/evidence/research.txt @@ -0,0 +1,4 @@ +Waiting 65 seconds for the real S3 LastModified grace (no timestamp forgery). + Container mtusi-lab4-s3-init-run-87a2b1a4c042 Creating + Container mtusi-lab4-s3-init-run-87a2b1a4c042 Created +PASS Track 2: both failures, dry-run, repair, repeat, fresh/used protection and measured scan cost diff --git a/evidence/restart-after.txt b/evidence/restart-after.txt new file mode 100644 index 00000000..e88cdc09 --- /dev/null +++ b/evidence/restart-after.txt @@ -0,0 +1,6 @@ +287d13f6fa5a05dd8138401a17605454a26b8ad1fde38063f89533046449a340 api 2026-10-30T17:34:47.995556812Z running +23cdf86873484ce293e835e836f619fa6d5b957f7c6e7224f0693e37ec3ae4f7 api 2026-10-30T17:34:47.782734394Z running +c6b006c443fae052885f0713df55a0f0d023d8be356f5b0e2c4c16ad3d58f56a db 2026-10-30T17:34:46.279164079Z running +61d73bbbe53995b02b88c8bb12b14f62cb4f54d42a2dd78ce1b564552701ad8d lb 2026-10-30T17:34:56.63772265Z running +72035d94e70ad3f996f34751c9533d7be313157a9001eb3df43e1e9a297ccaaf s3 2026-10-30T17:34:46.171817681Z running +96dc99b9811ca66a62e2917dbec82d101ce70d483715c50663c97aff7b032ae0 valkey 2026-10-30T17:34:46.422221358Z running diff --git a/evidence/restart-before.txt b/evidence/restart-before.txt new file mode 100644 index 00000000..121e5786 --- /dev/null +++ b/evidence/restart-before.txt @@ -0,0 +1,6 @@ +287d13f6fa5a05dd8138401a17605454a26b8ad1fde38063f89533046449a340 api 2026-10-30T17:33:31.254669056Z running +23cdf86873484ce293e835e836f619fa6d5b957f7c6e7224f0693e37ec3ae4f7 api 2026-10-30T17:33:30.967453639Z running +c6b006c443fae052885f0713df55a0f0d023d8be356f5b0e2c4c16ad3d58f56a db 2026-10-30T17:20:40.094358694Z running +61d73bbbe53995b02b88c8bb12b14f62cb4f54d42a2dd78ce1b564552701ad8d lb 2026-10-30T17:20:40.921943998Z running +72035d94e70ad3f996f34751c9533d7be313157a9001eb3df43e1e9a297ccaaf s3 2026-10-30T17:22:13.846912487Z running +96dc99b9811ca66a62e2917dbec82d101ce70d483715c50663c97aff7b032ae0 valkey 2026-10-30T17:20:40.048793768Z running diff --git a/evidence/restore-1.txt b/evidence/restore-1.txt new file mode 100644 index 00000000..7d4a6893 --- /dev/null +++ b/evidence/restore-1.txt @@ -0,0 +1,3 @@ + Container mtusi-lab4-api-1 Running + Container mtusi-lab4-api-2 Starting + Container mtusi-lab4-api-2 Started diff --git a/evidence/restore-2.txt b/evidence/restore-2.txt new file mode 100644 index 00000000..b9d40513 --- /dev/null +++ b/evidence/restore-2.txt @@ -0,0 +1,3 @@ + Container mtusi-lab4-api-2 Running + Container mtusi-lab4-api-1 Starting + Container mtusi-lab4-api-1 Started diff --git a/evidence/security-extra.json b/evidence/security-extra.json new file mode 100644 index 00000000..57fe5e06 --- /dev/null +++ b/evidence/security-extra.json @@ -0,0 +1,46 @@ +{ + "timestamp_utc": "2026-10-30T17:39:39.323699+00:00", + "api": [ + { + "id": "bad03eba0f797ecf9b4533dc9a481928857468ec6b724f0df913a6a208f38d23", + "instance": "bad03eba0f79", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "security_options": [ + "no-new-privileges:true" + ], + "tmpfs": { + "/tmp": "size=64m,mode=1777,noexec,nosuid,nodev" + }, + "memory_bytes": 805306368, + "oom_killed": false + }, + { + "id": "7d3983584e28c15354b148f486a7cf6d688929bcf2fcd62d0208f02b4fa95eab", + "instance": "7d3983584e28", + "user": "65532:65532", + "read_only": true, + "cap_drop": [ + "ALL" + ], + "security_options": [ + "no-new-privileges:true" + ], + "tmpfs": { + "/tmp": "size=64m,mode=1777,noexec,nosuid,nodev" + }, + "memory_bytes": 805306368, + "oom_killed": false + } + ], + "godebug": "madvdontneed=0", + "object_store_internal": true, + "object_store_members": [ + "mtusi-lab4-lb-1", + "mtusi-lab4-s3-1" + ], + "direct_backend_probe": "PASS: a temporary container on mtusi-lab4_default could not GET the actual MinIO backend IP (2-second timeout); separately observed in this session before final integration; network configuration unchanged" +} diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..c554fd6f --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1 @@ +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/stopped-after.txt b/evidence/stopped-after.txt new file mode 100644 index 00000000..fb155bef --- /dev/null +++ b/evidence/stopped-after.txt @@ -0,0 +1 @@ +b0d098842044763b9251c2e88bebe2bb4f39e30eb79307d7251d1bc91cf0149d exited 2026-10-30T17:35:28.72031777Z 0 diff --git a/evidence/stopped-before.txt b/evidence/stopped-before.txt new file mode 100644 index 00000000..f262e0bb --- /dev/null +++ b/evidence/stopped-before.txt @@ -0,0 +1 @@ +b0d098842044763b9251c2e88bebe2bb4f39e30eb79307d7251d1bc91cf0149d running 2026-10-30T17:35:00.949717443Z diff --git a/evidence/student-unit.txt b/evidence/student-unit.txt new file mode 100644 index 00000000..a9e3eb5e --- /dev/null +++ b/evidence/student-unit.txt @@ -0,0 +1,41 @@ +..... +---------------------------------------------------------------------- +Ran 5 tests in 0.066s + +OK +=== RUN TestPasswordHashSaltAndFullUnicode +--- PASS: TestPasswordHashSaltAndFullUnicode (0.46s) +=== RUN TestCursorIntegrityResourceAndRestart +--- PASS: TestCursorIntegrityResourceAndRestart (0.00s) +=== RUN TestStrictJSON +--- PASS: TestStrictJSON (0.00s) +=== RUN TestAttachmentFilename +--- PASS: TestAttachmentFilename (0.00s) +=== RUN TestAttachmentMessageValidation +--- PASS: TestAttachmentMessageValidation (0.00s) +=== RUN TestUntrustedImagesRejectedBeforeStorage +=== RUN TestUntrustedImagesRejectedBeforeStorage/empty +=== RUN TestUntrustedImagesRejectedBeforeStorage/invalid_bytes +=== RUN TestUntrustedImagesRejectedBeforeStorage/truncated_PNG +=== RUN TestUntrustedImagesRejectedBeforeStorage/truncated_JPEG +=== RUN TestUntrustedImagesRejectedBeforeStorage/spoof_PNG +=== RUN TestUntrustedImagesRejectedBeforeStorage/spoof_JPEG +=== RUN TestUntrustedImagesRejectedBeforeStorage/unsupported_MIME +=== RUN TestUntrustedImagesRejectedBeforeStorage/large_header +=== RUN TestUntrustedImagesRejectedBeforeStorage/chunked_bytes_limit +=== RUN TestUntrustedImagesRejectedBeforeStorage/pixel_guard +--- PASS: TestUntrustedImagesRejectedBeforeStorage (0.02s) + --- PASS: TestUntrustedImagesRejectedBeforeStorage/empty (0.00s) + --- PASS: TestUntrustedImagesRejectedBeforeStorage/invalid_bytes (0.00s) + --- PASS: TestUntrustedImagesRejectedBeforeStorage/truncated_PNG (0.00s) + --- PASS: TestUntrustedImagesRejectedBeforeStorage/truncated_JPEG (0.00s) + --- PASS: TestUntrustedImagesRejectedBeforeStorage/spoof_PNG (0.00s) + --- PASS: TestUntrustedImagesRejectedBeforeStorage/spoof_JPEG (0.00s) + --- PASS: TestUntrustedImagesRejectedBeforeStorage/unsupported_MIME (0.00s) + --- PASS: TestUntrustedImagesRejectedBeforeStorage/large_header (0.00s) + --- PASS: TestUntrustedImagesRejectedBeforeStorage/chunked_bytes_limit (0.01s) + --- PASS: TestUntrustedImagesRejectedBeforeStorage/pixel_guard (0.00s) +=== RUN TestReconcilerDistinguishesStorageFaults +--- PASS: TestReconcilerDistinguishesStorageFaults (0.00s) +PASS +ok mtusi-messenger 4.877s diff --git a/evidence/upload-memory-admission-4.json b/evidence/upload-memory-admission-4.json new file mode 100644 index 00000000..68105eaa --- /dev/null +++ b/evidence/upload-memory-admission-4.json @@ -0,0 +1,228 @@ +{ + "complete": true, + "method": "10 simultaneous clients, no retries; docker stats CPU/RAM plus kernel cgroup-v2 memory.peak; API cgroups recreated per case. Sum of individual peaks is an upper bound on simultaneous total peak.", + "cases": [ + { + "file_bytes": 207687, + "pixels": 65536, + "concurrency": 10, + "requests": 10, + "success": 4, + "backpressure_503": 6, + "error_fraction": 0.6, + "successful_rps": 1.9044784095475915, + "duration_seconds": 2.1003125999995973, + "p50_seconds": 2.090941299989936, + "p95_seconds": 2.0952364999975543, + "p99_seconds": 2.0952364999975543, + "baseline_bytes": 144703488, + "sampled_peak_bytes": 151005430, + "baseline_cgroups": [ + { + "memory.current": 77324288, + "memory.peak": 77324288 + }, + { + "memory.current": 77221888, + "memory.peak": 77221888 + } + ], + "peak_cgroups": [ + { + "memory.current": 79790080, + "memory.peak": 79790080 + }, + { + "memory.current": 79736832, + "memory.peak": 79736832 + } + ], + "sum_cgroup_peaks_bytes": 159526912, + "samples": [ + { + "t": 95273.7633672, + "total_bytes": 144703488, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "69.31MiB / 768MiB", + "CPUPerc": "0.39%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "68.69MiB / 768MiB", + "CPUPerc": "0.38%" + } + ] + }, + { + "t": 95275.8241669, + "total_bytes": 145573806, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "69.76MiB / 768MiB", + "CPUPerc": "0.35%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "69.07MiB / 768MiB", + "CPUPerc": "0.32%" + } + ] + }, + { + "t": 95277.8819649, + "total_bytes": 149537423, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "71.32MiB / 768MiB", + "CPUPerc": "0.34%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "71.29MiB / 768MiB", + "CPUPerc": "0.39%" + } + ] + }, + { + "t": 95279.8978409, + "total_bytes": 151005430, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "72.41MiB / 768MiB", + "CPUPerc": "5.49%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "71.6MiB / 768MiB", + "CPUPerc": "2.60%" + } + ] + } + ] + }, + { + "file_bytes": 7466790, + "pixels": 2359296, + "concurrency": 10, + "requests": 10, + "success": 4, + "backpressure_503": 6, + "error_fraction": 0.6, + "successful_rps": 1.042656837681367, + "duration_seconds": 3.836353299993789, + "p50_seconds": 3.489761200005887, + "p95_seconds": 3.8327185999951325, + "p99_seconds": 3.8327185999951325, + "baseline_bytes": 143696855, + "sampled_peak_bytes": 208089907, + "baseline_cgroups": [ + { + "memory.current": 77160448, + "memory.peak": 77160448 + }, + { + "memory.current": 75128832, + "memory.peak": 75128832 + } + ], + "peak_cgroups": [ + { + "memory.current": 100597760, + "memory.peak": 114049024 + }, + { + "memory.current": 101150720, + "memory.peak": 111169536 + } + ], + "sum_cgroup_peaks_bytes": 225218560, + "samples": [ + { + "t": 95287.4687733, + "total_bytes": 143696855, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "68.61MiB / 768MiB", + "CPUPerc": "0.80%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "68.43MiB / 768MiB", + "CPUPerc": "0.43%" + } + ] + }, + { + "t": 95289.5000525, + "total_bytes": 144944660, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "69.23MiB / 768MiB", + "CPUPerc": "0.72%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "69MiB / 768MiB", + "CPUPerc": "0.49%" + } + ] + }, + { + "t": 95291.5119588, + "total_bytes": 208089907, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "99.66MiB / 768MiB", + "CPUPerc": "14.14%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "98.79MiB / 768MiB", + "CPUPerc": "10.13%" + } + ] + }, + { + "t": 95293.5524877, + "total_bytes": 194080932, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "92.62MiB / 768MiB", + "CPUPerc": "5.04%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "92.47MiB / 768MiB", + "CPUPerc": "3.74%" + } + ] + }, + { + "t": 95295.5980135, + "total_bytes": 193818788, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "93.16MiB / 768MiB", + "CPUPerc": "0.48%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "91.68MiB / 768MiB", + "CPUPerc": "0.85%" + } + ] + } + ] + } + ] +} diff --git a/evidence/upload-memory.json b/evidence/upload-memory.json new file mode 100644 index 00000000..a29a3843 --- /dev/null +++ b/evidence/upload-memory.json @@ -0,0 +1,212 @@ +{ + "complete": true, + "method": "10 simultaneous clients, no retries; docker stats CPU/RAM plus kernel cgroup-v2 memory.peak; API cgroups recreated per case. Sum of individual peaks is an upper bound on simultaneous total peak.", + "cases": [ + { + "file_bytes": 207687, + "pixels": 65536, + "concurrency": 10, + "requests": 10, + "success": 10, + "backpressure_503": 0, + "error_fraction": 0.0, + "successful_rps": 6.332330988655537, + "duration_seconds": 1.5791973000013968, + "p50_seconds": 1.4107216999982484, + "p95_seconds": 1.5757480999891413, + "p99_seconds": 1.5757480999891413, + "baseline_bytes": 147052299, + "sampled_peak_bytes": 155786936, + "baseline_cgroups": [ + { + "memory.current": 75612160, + "memory.peak": 75612160 + }, + { + "memory.current": 77545472, + "memory.peak": 77545472 + } + ], + "peak_cgroups": [ + { + "memory.current": 81932288, + "memory.peak": 81932288 + }, + { + "memory.current": 81616896, + "memory.peak": 85520384 + } + ], + "sum_cgroup_peaks_bytes": 167452672, + "samples": [ + { + "t": 103787.1242098, + "total_bytes": 147052299, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "70.14MiB / 768MiB", + "CPUPerc": "7.20%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "70.1MiB / 768MiB", + "CPUPerc": "0.52%" + } + ] + }, + { + "t": 103789.1592151, + "total_bytes": 155786936, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "74.21MiB / 768MiB", + "CPUPerc": "2.39%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "74.36MiB / 768MiB", + "CPUPerc": "2.00%" + } + ] + }, + { + "t": 103791.1856362, + "total_bytes": 155671593, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "73.89MiB / 768MiB", + "CPUPerc": "0.61%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "74.57MiB / 768MiB", + "CPUPerc": "0.90%" + } + ] + } + ] + }, + { + "file_bytes": 7466790, + "pixels": 2359296, + "concurrency": 10, + "requests": 10, + "success": 10, + "backpressure_503": 0, + "error_fraction": 0.0, + "successful_rps": 1.760477278066049, + "duration_seconds": 5.680277799998294, + "p50_seconds": 4.48676629998954, + "p95_seconds": 5.678354400006356, + "p99_seconds": 5.678354400006356, + "baseline_bytes": 146622382, + "sampled_peak_bytes": 314887373, + "baseline_cgroups": [ + { + "memory.current": 76034048, + "memory.peak": 76353536 + }, + { + "memory.current": 78921728, + "memory.peak": 78921728 + } + ], + "peak_cgroups": [ + { + "memory.current": 131788800, + "memory.peak": 157995008 + }, + { + "memory.current": 130334720, + "memory.peak": 162095104 + } + ], + "sum_cgroup_peaks_bytes": 320090112, + "samples": [ + { + "t": 103799.6723452, + "total_bytes": 146622382, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "69.63MiB / 768MiB", + "CPUPerc": "0.52%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "70.2MiB / 768MiB", + "CPUPerc": "0.45%" + } + ] + }, + { + "t": 103801.6795483, + "total_bytes": 314887373, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "150.7MiB / 768MiB", + "CPUPerc": "92.34%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "149.6MiB / 768MiB", + "CPUPerc": "87.04%" + } + ] + }, + { + "t": 103803.8871612, + "total_bytes": 307127910, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "142.4MiB / 768MiB", + "CPUPerc": "1.58%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "150.5MiB / 768MiB", + "CPUPerc": "1.44%" + } + ] + }, + { + "t": 103805.9074708, + "total_bytes": 254908826, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "122MiB / 768MiB", + "CPUPerc": "7.77%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "121.1MiB / 768MiB", + "CPUPerc": "4.01%" + } + ] + }, + { + "t": 103807.9171466, + "total_bytes": 253021389, + "containers": [ + { + "Name": "mtusi-lab4-api-1", + "MemUsage": "120.5MiB / 768MiB", + "CPUPerc": "0.58%" + }, + { + "Name": "mtusi-lab4-api-2", + "MemUsage": "120.8MiB / 768MiB", + "CPUPerc": "0.68%" + } + ] + } + ] + } + ] +} diff --git a/evidence/verification.json b/evidence/verification.json new file mode 100644 index 00000000..e5618796 --- /dev/null +++ b/evidence/verification.json @@ -0,0 +1,293 @@ +{ + "started_utc": "2026-10-30T17:32:53.444369+00:00", + "complete": true, + "checks": [ + { + "name": "contract", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "scripts/check_contract.py" + ], + "exit_code": 0, + "seconds": 0.138 + }, + { + "name": "go-test", + "command": [ + "go", + "test", + "./..." + ], + "exit_code": 0, + "seconds": 5.41 + }, + { + "name": "go-vet", + "command": [ + "go", + "vet", + "./..." + ], + "exit_code": 0, + "seconds": 0.78 + }, + { + "name": "student-unit", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "student-tests/unit.py" + ], + "exit_code": 0, + "seconds": 8.884 + }, + { + "name": "go-vuln", + "command": [ + "go", + "run", + "golang.org/x/vuln/cmd/govulncheck@v1.1.4", + "./..." + ], + "exit_code": 0, + "seconds": 4.982 + }, + { + "name": "bootstrap", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "scripts/bootstrap.py" + ], + "exit_code": 0, + "seconds": 0.108 + }, + { + "name": "compose-config", + "command": [ + "docker", + "compose", + "config", + "--quiet" + ], + "exit_code": 0, + "seconds": 0.532 + }, + { + "name": "start", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "scripts/manage.py", + "start" + ], + "exit_code": 0, + "seconds": 22.452 + }, + { + "name": "build-tests", + "command": [ + "docker", + "build", + "-f", + "Dockerfile.tests", + "-t", + "mtusi-messenger:lab4-tests", + "." + ], + "exit_code": 0, + "seconds": 1.33 + }, + { + "name": "openapi", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "scripts/linux_tests.py", + "validate" + ], + "exit_code": 0, + "seconds": 3.173 + }, + { + "name": "go-race", + "command": [ + "docker", + "run", + "--rm", + "--mount", + "type=bind,source=C:\\Users\\maxsi\\lab4\\mtusi2026lab4-fork,target=/workspace", + "mtusi-messenger:lab4-tests", + "go", + "test", + "-race", + "./..." + ], + "exit_code": 0, + "seconds": 50.4 + }, + { + "name": "smoke", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "tests/smoke.py" + ], + "exit_code": 0, + "seconds": 6.144 + }, + { + "name": "attachments", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "student-tests/attachments.py" + ], + "exit_code": 0, + "seconds": 2.309 + }, + { + "name": "persistence", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "scripts/linux_tests.py", + "test-persistence" + ], + "exit_code": 0, + "seconds": 16.616 + }, + { + "name": "ready-before-failover", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "scripts/manage.py", + "restore" + ], + "exit_code": 0, + "seconds": 4.723 + }, + { + "name": "failover-1", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "scripts/linux_tests.py", + "test-failover" + ], + "exit_code": 0, + "seconds": 18.656 + }, + { + "name": "restore-1", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "scripts/manage.py", + "restore" + ], + "exit_code": 0, + "seconds": 2.349 + }, + { + "name": "failover-2", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "scripts/linux_tests.py", + "test-failover" + ], + "exit_code": 0, + "seconds": 17.823 + }, + { + "name": "restore-2", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "scripts/manage.py", + "restore" + ], + "exit_code": 0, + "seconds": 1.614 + }, + { + "name": "failures", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "student-tests/failures.py" + ], + "exit_code": 0, + "seconds": 30.976 + }, + { + "name": "memory", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "student-tests/memory.py" + ], + "exit_code": 0, + "seconds": 28.649 + }, + { + "name": "research", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "student-tests/research.py" + ], + "exit_code": 0, + "seconds": 120.647 + }, + { + "name": "load", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "tests/load.py", + "--duration", + "30", + "--concurrency", + "4", + "--output", + "evidence/load.json" + ], + "exit_code": 0, + "seconds": 35.234 + }, + { + "name": "infrastructure", + "command": [ + "C:\\Python314\\python.exe", + "-X", + "utf8", + "scripts/manage.py", + "status" + ], + "exit_code": 0, + "seconds": 3.879 + } + ], + "protected_unchanged": true +} diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..15d5a64c --- /dev/null +++ b/go.mod @@ -0,0 +1,37 @@ +module mtusi-messenger + +go 1.26.0 + +toolchain go1.27.3 + +require ( + github.com/jackc/pgx/v5 v5.9.2 + github.com/minio/minio-go/v7 v7.4.1 + github.com/redis/go-redis/v9 v9.12.1 + golang.org/x/crypto v0.57.0 +) + +require ( + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/google/uuid v1.6.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.19.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.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/net v0.60.0 // indirect + golang.org/x/sync v0.23.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect + gopkg.in/ini.v1 v1.67.3 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..53609ae4 --- /dev/null +++ b/go.sum @@ -0,0 +1,77 @@ +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/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/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/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/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw= +github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8= +github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM= +github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw= +github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI= +github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= +github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= +github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= +github.com/minio/minio-go/v7 v7.4.1 h1:PtU/zIOfQRWZ+QydXAZysc+xZYHdG+BBR4Z6TUvy73w= +github.com/minio/minio-go/v7 v7.4.1/go.mod h1:nQnQi7zTfXR4lREtYXZQWqo5aw0Rqv+ZqCGrTORygRk= +github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= +github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.12.1 h1:k5iquqv27aBtnTm2tIkROUDp8JBXhXZIVu1InSgvovg= +github.com/redis/go-redis/v9 v9.12.1/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= +github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/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.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.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +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= diff --git a/idempotency.go b/idempotency.go new file mode 100644 index 00000000..26557e61 --- /dev/null +++ b/idempotency.go @@ -0,0 +1,77 @@ +package main + +import ( + "context" + "errors" + "slices" + "sort" + "time" + + "github.com/jackc/pgx/v5" +) + +// The advisory lock serializes this key across processes. Message and result +// commit together; an interrupted/rolled-back transaction reserves nothing. +func (a *App) createMessage(ctx context.Context, chat, user, key, text string, ids []string) (Message, error) { + m := Message{ChatID: chat, SenderID: user, Text: text, AttachmentIDs: ids} + tx, err := a.db.Begin(ctx) + if err != nil { + return m, unavailable() + } + defer tx.Rollback(ctx) + // POST and the canonical chat path are implicit in this dedicated table. + if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", user+":"+chat+":"+key); err != nil { + return m, unavailable() + } + var previous Message + var created time.Time + err = tx.QueryRow(ctx, `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at,ARRAY(SELECT unnest(m.attachment_ids)::text) + FROM message_keys k JOIN messages m ON m.id=k.message_id + WHERE k.user_id=$1 AND k.chat_id=$2 AND k.key=$3 AND k.expires_at>clock_timestamp()`, user, chat, key).Scan(&previous.ID, &previous.ChatID, &previous.SenderID, utf8String{&previous.Text}, &created, &previous.AttachmentIDs) + if err == nil { + if previous.Text != text || !slices.Equal(previous.AttachmentIDs, ids) { + return m, apiError{409, "conflict", "Idempotency key has a different message"} + } + previous.CreatedAt = stamp(created) + return previous, nil + } + if !errors.Is(err, pgx.ErrNoRows) { + return m, unavailable() + } + if _, err = tx.Exec(ctx, "DELETE FROM message_keys WHERE user_id=$1 AND chat_id=$2 AND key=$3", user, chat, key); err != nil { + return m, unavailable() + } + // Serialize with reconciler; stable ordering prevents cross-upload deadlocks. + locked := slices.Clone(ids) + sort.Strings(locked) + for _, id := range locked { + if err = attachmentLock(ctx, tx, id); err != nil { + return m, unavailable() + } + var missingSince *time.Time + err = tx.QueryRow(ctx, "SELECT missing_since FROM attachments WHERE id=$1 AND chat_id=$2", id, chat).Scan(&missingSince) + if err != nil { + return m, dbError(err) + } + if missingSince != nil { + return m, unavailable() + } + } + m.ID = uuid() + if err = tx.QueryRow(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,attachment_ids) VALUES($1,$2,$3,$4,$5) RETURNING created_at", m.ID, chat, user, []byte(text), ids).Scan(&created); err != nil { + return m, dbError(err) + } + if _, err = tx.Exec(ctx, "INSERT INTO message_keys(user_id,chat_id,key,message_id,expires_at) VALUES($1,$2,$3,$4,clock_timestamp()+$5::bigint*interval '1 second')", user, chat, key, m.ID, int64(a.idempotencyTTL.Seconds())); err != nil { + return m, unavailable() + } + for _, id := range ids { + if _, err = tx.Exec(ctx, "INSERT INTO message_attachments(message_id,chat_id,attachment_id) VALUES($1,$2,$3)", m.ID, chat, id); err != nil { + return m, dbError(err) + } + } + if err = tx.Commit(ctx); err != nil { + return m, unavailable() + } + m.CreatedAt = stamp(created) + return m, nil +} diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg new file mode 100644 index 00000000..310924ac --- /dev/null +++ b/infra/haproxy.cfg @@ -0,0 +1,62 @@ +global + log stdout format raw local0 + maxconn 2048 + +defaults + log global + mode http + option httplog + timeout connect 500ms + timeout client 40s + timeout server 40s + timeout http-request 3s + timeout http-keep-alive 5s + timeout check 500ms + retries 0 + +resolvers docker + nameserver dns 127.0.0.11:53 + accepted_payload_size 8192 + resolve_retries 2 + timeout resolve 1s + timeout retry 1s + hold valid 1s + hold obsolete 1s + hold nx 1s + +frontend public + bind :8080 + default_backend api + +backend api + balance roundrobin + option httpchk + http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api + http-check expect status 200 + server-template replica 1-4 api:8080 check inter 500ms fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none + +listen stats + bind :8404 + stats enable + stats uri /stats + +# MinIO is reachable only through this internal listener. Public port 9000 is +# never published. Block unsupported vulnerable features in the archived CE. +frontend private_s3 + bind :9000 + no log + acl unsigned_trailer req.hdr(x-amz-content-sha256) -i STREAMING-UNSIGNED-PAYLOAD-TRAILER + http-request deny deny_status 403 if unsigned_trailer + acl internal_storage path,url_dec -m beg -i /minio/storage /minio/peer /minio/grid /minio/bootstrap + http-request deny deny_status 403 if internal_storage + acl s3_select query,url_dec -m reg -i '(^|&)select([=&]|$)' + http-request deny deny_status 403 if s3_select + acl replication_header req.hdr(x-minio-source-replication-request) -m found + http-request deny deny_status 403 if replication_header + default_backend minio_private + +backend minio_private + option httpchk + http-check send meth GET uri /minio/health/ready ver HTTP/1.1 hdr Host minio-backend + http-check expect status 200 + server minio minio-backend:9000 check inter 1s resolvers docker init-addr none diff --git a/infra/s3-health.go b/infra/s3-health.go new file mode 100644 index 00000000..718aa1b6 --- /dev/null +++ b/infra/s3-health.go @@ -0,0 +1,20 @@ +// Standalone health probe for the minimal MinIO container. +package main + +import ( + "net/http" + "os" + "time" +) + +func main() { + client := http.Client{Timeout: time.Second} + response, err := client.Get("http://127.0.0.1:9000/minio/health/ready") + if err != nil { + os.Exit(1) + } + response.Body.Close() + if response.StatusCode != 200 { + os.Exit(1) + } +} diff --git a/infra/s3-init.sh b/infra/s3-init.sh new file mode 100644 index 00000000..f4067a33 --- /dev/null +++ b/infra/s3-init.sh @@ -0,0 +1,14 @@ +#!/bin/sh +set -eu +# No shell tracing and no credentials in persistent config or output. +for attempt in $(seq 1 30); do + if wget -q -O /dev/null http://s3:9000/minio/health/ready; then break; fi + sleep 1 +done +mc alias set local http://s3:9000 "$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null +mc mb --ignore-existing local/messenger-attachments >/dev/null +mc anonymous set none local/messenger-attachments >/dev/null +mc admin user add local "$(cat /run/secrets/s3_access_key_id)" "$(cat /run/secrets/s3_secret_access_key)" >/dev/null +mc admin policy create local messenger-api /bootstrap/policy.json >/dev/null +mc admin policy attach local messenger-api --user "$(cat /run/secrets/s3_access_key_id)" >/dev/null +echo 'Private bucket and restricted API account ready.' diff --git a/infra/s3-policy.json b/infra/s3-policy.json new file mode 100644 index 00000000..322c41c6 --- /dev/null +++ b/infra/s3-policy.json @@ -0,0 +1,7 @@ +{ + "Version":"2012-10-17", + "Statement":[ + {"Effect":"Allow","Action":["s3:GetBucketLocation","s3:ListBucket"],"Resource":["arn:aws:s3:::messenger-attachments"]}, + {"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::messenger-attachments/original/*"]} + ] +} diff --git a/main.go b/main.go new file mode 100644 index 00000000..4cd67759 --- /dev/null +++ b/main.go @@ -0,0 +1,444 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "strconv" + "strings" + "sync/atomic" + "syscall" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + "github.com/minio/minio-go/v7" + "github.com/redis/go-redis/v9" +) + +type App struct { + db *pgxpool.Pool + sessions *redis.Client + secret []byte + ttl time.Duration + slots, kdf chan struct{} + stopping atomic.Bool + dummyHash string + instance string + idempotencyTTL time.Duration + s3 *minio.Client + bucket string + uploadSlots, decodeSlot chan struct{} +} + +func env(key, value string) string { + if v := os.Getenv(key); v != "" { + return v + } + return value +} +func positive(key string, fallback int) int { + n, e := strconv.Atoi(env(key, strconv.Itoa(fallback))) + if e != nil || n <= 0 { + panic("invalid positive configuration: " + key) + } + return n +} +func secretFile(key string) (string, error) { + b, e := os.ReadFile(os.Getenv(key)) + if e != nil { + return "", fmt.Errorf("cannot read %s", key) + } + s := strings.TrimSpace(string(b)) + if s == "" { + return "", fmt.Errorf("empty %s", key) + } + return s, nil +} + +func (a *App) dispatch(ctx context.Context, w http.ResponseWriter, r *http.Request) (int, any, error) { + path := r.URL.Path + if r.Method == "GET" && (path == "/health/live" || path == "/health/ready") { + if path == "/health/ready" && (a.stopping.Load() || a.db.Ping(ctx) != nil || a.sessions.Ping(ctx).Err() != nil || !a.s3Ready(ctx)) { + return 0, nil, unavailable() + } + return 200, map[string]string{"status": "ok"}, nil + } + if a.stopping.Load() { + return 0, nil, unavailable() + } + if r.Method == "POST" && path == "/api/v1/auth/sessions" { + return a.login(ctx, r) + } + if r.Method == "POST" && path == "/api/v1/users" { + body, err := readObject(w, r, 128*1024, []string{"username", "display_name", "password"}) + if err != nil { + return 0, nil, err + } + name, err := textField(body, "username", 32) + if err != nil || !usernamePattern.MatchString(name) { + return 0, nil, invalid() + } + display, err := textField(body, "display_name", 100) + if err != nil { + return 0, nil, err + } + p, err := password(body) + if err != nil { + return 0, nil, err + } + if err = a.kdfSlot(ctx); err != nil { + return 0, nil, err + } + hash := hashPassword(p) + <-a.kdf + u, err := scanUser(a.db.QueryRow(ctx, "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4) RETURNING id::text,username,display_name,created_at", uuid(), name, []byte(display), hash)) + return 201, u, err + } + user, key, err := a.authenticate(ctx, r) + if err != nil { + return 0, nil, err + } + if r.Method == "DELETE" && path == "/api/v1/auth/sessions/current" { + count, e := a.sessions.Del(ctx, key).Result() + if e != nil { + return 0, nil, unavailable() + } + if count == 0 { + return 0, nil, unauthorized() + } + return 204, nil, nil + } + if r.Method == "GET" && path == "/api/v1/users/me" { + u, e := a.user(ctx, user) + return 200, u, e + } + if path == "/api/v1/chats" { + if r.Method == "GET" { + scope := "chats:" + user + limit, c, e := a.pagination(r, scope) + if e != nil { + return 0, nil, e + } + page, e := a.listChats(ctx, user, limit, c, scope) + return 200, page, e + } + if r.Method == "POST" { + body, e := readObject(w, r, 128*1024, []string{"title", "member_ids"}) + if e != nil { + return 0, nil, e + } + title, e := textField(body, "title", 100) + if e != nil { + return 0, nil, e + } + var ids []string + if json.Unmarshal(body["member_ids"], &ids) != nil || len(ids) < 1 || len(ids) > 100 { + return 0, nil, invalid() + } + seen := map[string]bool{} + for i, id := range ids { + normalized, e := normalizeID(id) + if e != nil || seen[normalized] { + return 0, nil, invalid() + } + ids[i] = normalized + seen[normalized] = true + } + if !seen[user] { + return 0, nil, invalid() + } + chat, e := a.createChat(ctx, title, ids) + return 201, chat, e + } + } + if strings.HasPrefix(path, "/api/v1/attachments/") { + parts := strings.Split(strings.TrimPrefix(path, "/api/v1/attachments/"), "/") + id, e := normalizeID(parts[0]) + if e != nil { + return 0, nil, e + } + if r.Method != "GET" || len(parts) > 2 || (len(parts) == 2 && parts[1] != "content") { + return 0, nil, missing() + } + x, e := a.attachment(ctx, id, user) + if e != nil { + return 0, nil, e + } + if len(parts) == 1 { + return 200, x, nil + } + b, e := a.content(ctx, r, x) + return 200, b, e + } + if strings.HasPrefix(path, "/api/v1/chats/") { + parts := strings.Split(strings.TrimPrefix(path, "/api/v1/chats/"), "/") + id, e := normalizeID(parts[0]) + if e != nil { + return 0, nil, e + } + if len(parts) > 2 || (len(parts) == 2 && parts[1] != "messages" && parts[1] != "attachments") { + return 0, nil, missing() + } + chat, e := a.chat(ctx, id, user) + if e != nil { + return 0, nil, e + } + if len(parts) == 1 && r.Method == "GET" { + return 200, chat, nil + } + if len(parts) == 2 && parts[1] == "attachments" { + if r.Method != "POST" { + return 0, nil, missing() + } + x, e := a.upload(ctx, w, r, id, user) + return 201, x, e + } + if len(parts) == 2 { + if r.Method == "GET" { + scope := "messages:" + id + limit, c, e := a.pagination(r, scope) + if e != nil { + return 0, nil, e + } + page, e := a.history(ctx, id, limit, c, scope) + return 200, page, e + } + if r.Method == "POST" { + keys := r.Header.Values("Idempotency-Key") + if len(keys) != 1 || !idempotencyPattern.MatchString(keys[0]) { + return 0, nil, invalid() + } + body, e := readObject(w, r, 128*1024, []string{"text", "attachment_ids"}) + if e != nil { + return 0, nil, e + } + text, ids, e := messageFields(body) + if e != nil { + return 0, nil, e + } + m, e := a.createMessage(ctx, id, user, keys[0], text, ids) + return 201, m, e + } + } + } + return 0, nil, missing() +} + +func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) { + start := time.Now() + requestID := uuid() + status := 500 + w.Header().Set("Content-Type", "application/json") + w.Header().Set("X-Request-Id", requestID) + w.Header().Set("X-Instance-Id", a.instance) + fail := func(err error) { + var e apiError + if !errors.As(err, &e) { + e = unavailable() + } + status = e.status + if status == 401 { + scheme := `Bearer realm="messenger"` + if r.URL.Path == "/api/v1/auth/sessions" { + scheme = `Basic realm="messenger", charset="UTF-8"` + } + w.Header().Set("WWW-Authenticate", scheme) + } + if status == 503 { + w.Header().Set("Retry-After", "1") + } + w.WriteHeader(status) + json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": e.code, "message": e.message, "request_id": requestID}}) + } + defer func() { + if recovered := recover(); recovered != nil { + if recovered == http.ErrAbortHandler { + panic(recovered) + } + fail(apiError{500, "internal_error", "Internal server error"}) + } + if env("REQUEST_LOG", "1") == "1" { + slog.Info("request", "method", r.Method, "status", status, "request_id", requestID, "duration_ms", time.Since(start).Milliseconds()) + } + }() + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + health := r.Method == "GET" && (r.URL.Path == "/health/live" || r.URL.Path == "/health/ready") + if !health { + select { + case a.slots <- struct{}{}: + defer func() { <-a.slots }() + default: + fail(unavailable()) + return + } + } + code, value, err := a.dispatch(ctx, w, r) + if err != nil { + fail(err) + return + } + status = code + if b, ok := value.(binaryContent); ok { + writeContent(w, b) + return + } + w.WriteHeader(code) + if code != 204 { + json.NewEncoder(w).Encode(value) + } +} + +func run() error { + if len(os.Args) > 1 && os.Args[1] == "memory-snapshot" { + return memorySnapshot() + } + if env("SESSION_STORE", "valkey") != "valkey" { + return errors.New("SESSION_STORE must be valkey") + } + address := net.JoinHostPort(env("APP_HOST", "0.0.0.0"), env("APP_PORT", "8080")) + if len(os.Args) > 1 && os.Args[1] == "reconcile" { + return runReconcile() + } + if len(os.Args) > 1 && os.Args[1] == "reconcile-loop" { + return reconcileLoop() + } + if len(os.Args) > 1 && os.Args[1] == "healthcheck" { + client := http.Client{Timeout: 2 * time.Second} + res, e := client.Get("http://127.0.0.1:" + env("APP_PORT", "8080") + "/health/ready") + if e != nil { + return errors.New("not ready") + } + defer res.Body.Close() + if res.StatusCode != 200 { + return errors.New("not ready") + } + return nil + } + dbURL, err := secretFile("DATABASE_URL_FILE") + if err != nil { + return err + } + cfg, err := pgxpool.ParseConfig(dbURL) + if err != nil { + return errors.New("invalid database configuration") + } + cfg.MaxConns = int32(positive("DB_POOL_MAX", 8)) + cfg.MinConns = 0 + cfg.ConnConfig.ConnectTimeout = 2 * time.Second + cfg.ConnConfig.RuntimeParams["statement_timeout"] = "3000" + cfg.ConnConfig.RuntimeParams["lock_timeout"] = "1000" + cfg.ConnConfig.RuntimeParams["synchronous_commit"] = "on" + startup, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + db, err := pgxpool.NewWithConfig(startup, cfg) + if err != nil { + return errors.New("database setup failed") + } + defer db.Close() + if len(os.Args) > 1 && os.Args[1] == "migrate" { + if err = migrate(startup, db); err != nil { + return fmt.Errorf("migration failed: %w", err) + } + slog.Info("migrations complete") + return nil + } + var schemaReady bool + if err = db.QueryRow(startup, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version='004_attachments.sql')").Scan(&schemaReady); err != nil || !schemaReady { + return errors.New("run the migrate service before starting API") + } + cacheURL, err := secretFile("CACHE_URL_FILE") + if err != nil { + return err + } + signing, err := secretFile("CURSOR_SECRET_FILE") + if err != nil { + return err + } + if len(signing) < 32 { + return errors.New("cursor secret too short") + } + options, err := redis.ParseURL(cacheURL) + if err != nil { + return errors.New("invalid session store configuration") + } + options.PoolSize = 8 + options.MaxActiveConns = 8 + options.DialTimeout = time.Second + options.ReadTimeout = time.Second + options.WriteTimeout = time.Second + options.PoolTimeout = time.Second + options.MaxRetries = -1 + options.ContextTimeoutEnabled = true + sessions := redis.NewClient(options) + defer sessions.Close() + hostname, err := os.Hostname() + if err != nil { + return errors.New("cannot identify instance") + } + s3, bucket, err := s3Client() + if err != nil { + return err + } + a := &App{s3: s3, bucket: bucket, uploadSlots: make(chan struct{}, 5), decodeSlot: make(chan struct{}, 1), db: db, sessions: sessions, secret: []byte(signing), ttl: time.Duration(positive("SESSION_TTL_SECONDS", 3600)) * time.Second, slots: make(chan struct{}, positive("MAX_INFLIGHT", 32)), kdf: make(chan struct{}, 2), dummyHash: hashPassword("unknown-user-dummy-password"), instance: hostname, idempotencyTTL: time.Duration(positive("IDEMPOTENCY_TTL_SECONDS", 86400)) * time.Second} + if a.idempotencyTTL < 24*time.Hour { + return errors.New("idempotency retention must be at least 24 hours") + } + server := &http.Server{Addr: address, Handler: a, ReadHeaderTimeout: 2 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 35 * time.Second, IdleTimeout: 5 * time.Second, MaxHeaderBytes: 16 * 1024} + listener, err := net.Listen("tcp", address) + if err != nil { + return errors.New("listen failed") + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if env("POOL_METRICS", "0") == "1" { + go func() { + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + s := db.Stat() + slog.Info("pool", "instance", a.instance, "acquired", s.AcquiredConns(), "max", s.MaxConns(), "empty_acquires", s.EmptyAcquireCount(), "acquire_ns", s.AcquireDuration().Nanoseconds()) + } + } + }() + } + done := make(chan struct{}) + go func() { + <-ctx.Done() + a.stopping.Store(true) + slog.Info("shutdown started") + // Allow two LB readiness checks to drain this backend before closing it. + time.Sleep(1500 * time.Millisecond) + shutdown, cancel := context.WithTimeout(context.Background(), 6*time.Second) + defer cancel() + err := server.Shutdown(shutdown) + if err != nil { + server.Close() + } + slog.Info("shutdown complete", "forced", err != nil) + close(done) + }() + slog.Info("listening", "address", address, "environment", env("APP_ENV", "lab"), "session_store", "valkey", "session_ttl_seconds", int(a.ttl.Seconds())) + if err = server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) { + return errors.New("serve failed") + } + <-done + return nil +} +func main() { + slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil))) + if err := run(); err != nil { + slog.Error("startup failed", "reason", err.Error()) + os.Exit(1) + } +} diff --git a/memory.go b/memory.go new file mode 100644 index 00000000..f1f46226 --- /dev/null +++ b/memory.go @@ -0,0 +1,27 @@ +package main + +import ( + "encoding/json" + "fmt" + "os" + "strconv" + "strings" +) + +// Local operator command, never an HTTP endpoint. cgroup v2 records peaks +// between Docker samples too; the experiment recreates API cgroups per case. +func memorySnapshot() error { + result := map[string]uint64{} + for _, name := range []string{"memory.current", "memory.peak"} { + raw, err := os.ReadFile("/sys/fs/cgroup/" + name) + if err != nil { + return fmt.Errorf("cgroup v2 %s unavailable", name) + } + value, err := strconv.ParseUint(strings.TrimSpace(string(raw)), 10, 64) + if err != nil { + return fmt.Errorf("invalid cgroup %s", name) + } + result[name] = value + } + return json.NewEncoder(os.Stdout).Encode(result) +} diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 00000000..69c00bb4 --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,28 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id), + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members(user_id, chat_id); +CREATE INDEX chats_page_idx ON chats(created_at, id); +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL, + text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id) +); +CREATE INDEX messages_history_idx ON messages(chat_id, created_at, id); diff --git a/migrations/002_unicode_storage.sql b/migrations/002_unicode_storage.sql new file mode 100644 index 00000000..19a1643f --- /dev/null +++ b/migrations/002_unicode_storage.sql @@ -0,0 +1,12 @@ +-- PostgreSQL text cannot contain U+0000, although it is a valid JSON string +-- code point. Keep exact UTF-8 bytes for free-form API strings. The API checks +-- Unicode length/whitespace; these checks also bound stored byte lengths. +ALTER TABLE users DROP CONSTRAINT users_display_name_check; +ALTER TABLE users ALTER COLUMN display_name TYPE bytea USING convert_to(display_name,'UTF8'); +ALTER TABLE users ADD CHECK (octet_length(display_name) BETWEEN 1 AND 400); +ALTER TABLE chats DROP CONSTRAINT chats_title_check; +ALTER TABLE chats ALTER COLUMN title TYPE bytea USING convert_to(title,'UTF8'); +ALTER TABLE chats ADD CHECK (octet_length(title) BETWEEN 1 AND 400); +ALTER TABLE messages DROP CONSTRAINT messages_text_check; +ALTER TABLE messages ALTER COLUMN text TYPE bytea USING convert_to(text,'UTF8'); +ALTER TABLE messages ADD CHECK (octet_length(text) BETWEEN 1 AND 16000); diff --git a/migrations/003_idempotency.sql b/migrations/003_idempotency.sql new file mode 100644 index 00000000..609c79df --- /dev/null +++ b/migrations/003_idempotency.sql @@ -0,0 +1,8 @@ +CREATE TABLE message_keys ( + user_id uuid NOT NULL REFERENCES users(id), + chat_id uuid NOT NULL REFERENCES chats(id), + key text NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'), + message_id uuid NOT NULL REFERENCES messages(id), + expires_at timestamptz NOT NULL, + PRIMARY KEY (user_id, chat_id, key) +); diff --git a/migrations/004_attachments.sql b/migrations/004_attachments.sql new file mode 100644 index 00000000..73a2d60b --- /dev/null +++ b/migrations/004_attachments.sql @@ -0,0 +1,27 @@ +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + owner_id uuid NOT NULL, + object_key text NOT NULL UNIQUE CHECK (object_key = 'original/' || id::text), + filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255), + content_type text NOT NULL CHECK (content_type IN ('image/png','image/jpeg')), + size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760), + sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), + missing_since timestamptz, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + UNIQUE (chat_id,id), + FOREIGN KEY (chat_id,owner_id) REFERENCES chat_members(chat_id,user_id) +); +CREATE INDEX attachments_page_idx ON attachments(id); +ALTER TABLE messages DROP CONSTRAINT messages_text_check; +ALTER TABLE messages ADD CHECK (octet_length(text) BETWEEN 0 AND 16000); +ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}'; +ALTER TABLE messages ADD CHECK (cardinality(attachment_ids) <= 10); +CREATE TABLE message_attachments ( + message_id uuid NOT NULL REFERENCES messages(id), + chat_id uuid NOT NULL, + attachment_id uuid NOT NULL, + PRIMARY KEY (message_id,attachment_id), + FOREIGN KEY (chat_id,attachment_id) REFERENCES attachments(chat_id,id) +); diff --git a/protocol.go b/protocol.go new file mode 100644 index 00000000..671941eb --- /dev/null +++ b/protocol.go @@ -0,0 +1,239 @@ +package main + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "io" + "mime" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" + "unicode/utf8" +) + +type User struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt string `json:"created_at"` +} +type Chat struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt string `json:"created_at"` +} +type Message struct { + AttachmentIDs []string `json:"attachment_ids"` + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt string `json:"created_at"` +} +type Page[T any] struct { + Items []T `json:"items"` + NextCursor *string `json:"next_cursor"` +} +type apiError struct { + status int + code, message string +} + +func (e apiError) Error() string { return e.code } +func invalid() apiError { return apiError{400, "invalid_request", "Invalid request"} } +func unavailable() apiError { return apiError{503, "unavailable", "Dependency unavailable"} } +func missing() apiError { return apiError{404, "not_found", "Object not found"} } +func unauthorized() apiError { return apiError{401, "unauthorized", "Valid Bearer session required"} } + +func uuid() string { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + panic(err) + } + b[6] = (b[6] & 15) | 64 + b[8] = (b[8] & 63) | 128 + s := hex.EncodeToString(b) + return s[:8] + "-" + s[8:12] + "-" + s[12:16] + "-" + s[16:20] + "-" + s[20:] +} + +var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) +var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) +var idempotencyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +func normalizeID(s string) (string, error) { + if !uuidPattern.MatchString(s) { + return "", invalid() + } + return strings.ToLower(s), nil +} + +func textField(m map[string]json.RawMessage, key string, max int) (string, error) { + var s string + b, ok := m[key] + if !ok || string(b) == "null" || json.Unmarshal(b, &s) != nil || strings.TrimSpace(s) == "" || utf8.RuneCountInString(s) > max { + return "", invalid() + } + return s, nil +} + +// Reject duplicate keys, invalid UTF-8, and unpaired UTF-16 escapes rather than +// letting encoding/json silently replace malformed Unicode with U+FFFD. +func validUnicode(b []byte) bool { + if !utf8.Valid(b) { + return false + } + for i := 0; i < len(b); i++ { + if b[i] != '\\' { + continue + } + i++ + if i >= len(b) { + return false + } + if b[i] != 'u' { + continue + } + if i+4 >= len(b) { + return false + } + n, e := strconv.ParseUint(string(b[i+1:i+5]), 16, 16) + if e != nil { + return false + } + i += 4 + if n >= 0xDC00 && n <= 0xDFFF { + return false + } + if n >= 0xD800 && n <= 0xDBFF { + if i+6 >= len(b) || string(b[i+1:i+3]) != `\u` { + return false + } + low, e := strconv.ParseUint(string(b[i+3:i+7]), 16, 16) + if e != nil || low < 0xDC00 || low > 0xDFFF { + return false + } + i += 6 + } + } + return true +} +func readObject(w http.ResponseWriter, r *http.Request, max int, fields []string) (map[string]json.RawMessage, error) { + media, params, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || media != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) { + return nil, apiError{415, "unsupported_media_type", "Expected application/json UTF-8"} + } + b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, int64(max))) + if err != nil { + var large *http.MaxBytesError + if errors.As(err, &large) { + return nil, apiError{413, "payload_too_large", "Request body exceeds byte limit"} + } + return nil, invalid() + } + if !validUnicode(b) { + return nil, invalid() + } + d := json.NewDecoder(strings.NewReader(string(b))) + token, err := d.Token() + if err != nil || token != json.Delim('{') { + return nil, invalid() + } + m := map[string]json.RawMessage{} + for d.More() { + t, err := d.Token() + if err != nil { + return nil, invalid() + } + key, ok := t.(string) + if !ok { + return nil, invalid() + } + allowed := false + for _, f := range fields { + if key == f { + allowed = true + } + } + if !allowed || m[key] != nil { + return nil, invalid() + } + var value json.RawMessage + if d.Decode(&value) != nil { + return nil, invalid() + } + m[key] = value + } + if _, err = d.Token(); err != nil { + return nil, invalid() + } + if _, err = d.Token(); err != io.EOF { + return nil, invalid() + } + return m, nil +} + +type cursor struct { + Scope string `json:"s"` + Time string `json:"t"` + ID string `json:"i"` +} + +func (a *App) encodeCursor(scope, t, id string) string { + b, _ := json.Marshal(cursor{scope, t, id}) + h := hmac.New(sha256.New, a.secret) + h.Write(b) + return base64.RawURLEncoding.EncodeToString(b) + "." + base64.RawURLEncoding.EncodeToString(h.Sum(nil)) +} +func (a *App) pagination(r *http.Request, scope string) (int, cursor, error) { + values, e := url.ParseQuery(r.URL.RawQuery) + if e != nil { + return 0, cursor{}, invalid() + } + limit := 50 + if v, ok := values["limit"]; ok { + if len(v) != 1 || v[0] == "" { + return 0, cursor{}, invalid() + } + for _, c := range v[0] { + if c < '0' || c > '9' { + return 0, cursor{}, invalid() + } + } + limit, e = strconv.Atoi(v[0]) + if e != nil || limit < 1 || limit > 100 { + return 0, cursor{}, invalid() + } + } + c := cursor{} + if v, ok := values["cursor"]; ok { + if len(v) != 1 || len(v[0]) > 1024 { + return 0, c, invalid() + } + parts := strings.Split(v[0], ".") + if len(parts) != 2 { + return 0, c, invalid() + } + b, e := base64.RawURLEncoding.DecodeString(parts[0]) + if e != nil { + return 0, c, invalid() + } + sig, e := base64.RawURLEncoding.DecodeString(parts[1]) + if e != nil { + return 0, c, invalid() + } + h := hmac.New(sha256.New, a.secret) + h.Write(b) + if !hmac.Equal(sig, h.Sum(nil)) || json.Unmarshal(b, &c) != nil || c.Scope != scope { + return 0, c, invalid() + } + } + return limit, c, nil +} diff --git a/reconcile.go b/reconcile.go new file mode 100644 index 00000000..b59de622 --- /dev/null +++ b/reconcile.go @@ -0,0 +1,309 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "log/slog" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/minio/minio-go/v7" +) + +type reconcileReport struct { + Apply bool `json:"apply"` + GraceSeconds int `json:"grace_seconds"` + Cutoff string `json:"cutoff"` + Objects int `json:"objects_scanned"` + Rows int `json:"metadata_scanned"` + Orphans int `json:"old_orphans"` + Fresh int `json:"fresh_protected"` + Used int `json:"metadata_protected"` + Busy int `json:"active_protected"` + Missing int `json:"missing"` + Recovered int `json:"recovered"` + Deleted int `json:"deleted"` + Marked int `json:"marked_unavailable"` + Cleared int `json:"cleared_unavailable"` + HeadRequests int `json:"head_requests"` + GetRequests int `json:"get_requests"` + VerifiedBytes int64 `json:"verified_bytes"` + ElapsedMS int64 `json:"elapsed_ms"` + Complete bool `json:"complete"` +} + +func absentObject(err error) bool { + e := minio.ToErrorResponse(err) + return e.Code == "NoSuchKey" || e.Code == "NoSuchObject" || (e.StatusCode == 404 && e.Code == "NotFound") +} + +// Same per-key lock as upload/message creation. Re-check PostgreSQL and HEAD +// after locking; a stale LIST snapshot can never authorize a deletion alone. +func (a *App) reconcileObject(ctx context.Context, key string, cutoff time.Time, apply bool, r *reconcileReport) error { + id := strings.TrimPrefix(key, "original/") + normalized, err := normalizeID(id) + if err != nil || id != normalized || key != "original/"+id { + return nil + } + tx, err := a.db.Begin(ctx) + if err != nil { + return err + } + defer rollbackAttachment(tx) + var locked bool + if err = tx.QueryRow(ctx, "SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))", "attachment:"+id).Scan(&locked); err != nil { + return err + } + if !locked { + r.Busy++ + return nil + } + var exists bool + if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)", key).Scan(&exists); err != nil { + return err + } + if exists { + r.Used++ + return nil + } + r.HeadRequests++ + info, err := a.s3.StatObject(ctx, a.bucket, key, minio.StatObjectOptions{}) + if absentObject(err) { + return nil + } + if err != nil { + return err + } + if !info.LastModified.Before(cutoff) { + r.Fresh++ + return nil + } + r.Orphans++ + if apply { + if err = a.s3.RemoveObject(ctx, a.bucket, key, minio.RemoveObjectOptions{}); err != nil { + return err + } + r.Deleted++ + } + return tx.Commit(ctx) +} + +type attachmentRecord struct { + id, key, checksum string + size int64 + created time.Time + missing *time.Time +} + +func (a *App) reconcileMetadata(ctx context.Context, row attachmentRecord, cutoff time.Time, apply bool, r *reconcileReport) error { + tx, err := a.db.Begin(ctx) + if err != nil { + return err + } + defer rollbackAttachment(tx) + var locked bool + if err = tx.QueryRow(ctx, "SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))", "attachment:"+row.id).Scan(&locked); err != nil { + return err + } + if !locked { + r.Busy++ + return nil + } + // Refresh after acquiring the lock, rather than acting on the page snapshot. + err = tx.QueryRow(ctx, "SELECT object_key,sha256,size_bytes,created_at,missing_since FROM attachments WHERE id=$1", row.id).Scan(&row.key, &row.checksum, &row.size, &row.created, &row.missing) + if errors.Is(err, pgx.ErrNoRows) { + return nil + } + if err != nil { + return err + } + if !row.created.Before(cutoff) { + r.Fresh++ + return nil + } + r.HeadRequests++ + info, err := a.s3.StatObject(ctx, a.bucket, row.key, minio.StatObjectOptions{}) + if err != nil && !absentObject(err) { + return err + } + if absentObject(err) { + r.Missing++ + // Keep metadata and message references: lost bytes cannot be reconstructed. + if apply && row.missing == nil { + if _, err = tx.Exec(ctx, "UPDATE attachments SET missing_since=clock_timestamp(),updated_at=clock_timestamp() WHERE id=$1", row.id); err != nil { + return err + } + r.Marked++ + } + } else if row.missing != nil { + if info.Size != row.size { + return fmt.Errorf("restored object has wrong size") + } + object, e := a.s3.GetObject(ctx, a.bucket, row.key, minio.GetObjectOptions{}) + if e != nil { + return e + } + r.GetRequests++ + hash := sha256.New() + n, e := io.Copy(hash, io.LimitReader(object, row.size+1)) + object.Close() + r.VerifiedBytes += n + if e != nil { + return e + } + if n != row.size || hex.EncodeToString(hash.Sum(nil)) != row.checksum { + return fmt.Errorf("restored object has wrong checksum") + } + r.Recovered++ + if apply { + if _, err = tx.Exec(ctx, "UPDATE attachments SET missing_since=NULL,updated_at=clock_timestamp() WHERE id=$1", row.id); err != nil { + return err + } + r.Cleared++ + } + } else if info.Size != row.size { + return fmt.Errorf("stored object has wrong size") + } + return tx.Commit(ctx) +} + +func (a *App) reconcile(ctx context.Context, apply bool, grace int) (reconcileReport, error) { + started := time.Now() + r := reconcileReport{Apply: apply, GraceSeconds: grace} + var now time.Time + if err := a.db.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); err != nil { + return r, err + } + cutoff := now.Add(-time.Duration(grace) * time.Second) + r.Cutoff = stamp(cutoff) + listing, cancel := context.WithCancel(ctx) + defer cancel() + for object := range a.s3.ListObjects(listing, a.bucket, minio.ListObjectsOptions{Prefix: "original/", Recursive: true, MaxKeys: 1000}) { + if object.Err != nil { + return r, object.Err + } + r.Objects++ + itemCtx, done := context.WithTimeout(ctx, 15*time.Second) + err := a.reconcileObject(itemCtx, object.Key, cutoff, apply, &r) + done() + if err != nil { + return r, err + } + } + last := "00000000-0000-0000-0000-000000000000" + for { + rows, err := a.db.Query(ctx, "SELECT id::text FROM attachments WHERE id>$1 ORDER BY id LIMIT 256", last) + if err != nil { + return r, err + } + page := []attachmentRecord{} + for rows.Next() { + var x attachmentRecord + if err = rows.Scan(&x.id); err != nil { + rows.Close() + return r, err + } + page = append(page, x) + } + err = rows.Err() + rows.Close() + if err != nil { + return r, err + } + for _, x := range page { + r.Rows++ + last = x.id + itemCtx, done := context.WithTimeout(ctx, 15*time.Second) + err = a.reconcileMetadata(itemCtx, x, cutoff, apply, &r) + done() + if err != nil { + return r, err + } + } + if len(page) < 256 { + break + } + } + r.ElapsedMS = time.Since(started).Milliseconds() + r.Complete = true + return r, nil +} + +func runReconcile() error { + return reconcileCommand(context.Background(), os.Args[2:]) +} + +func reconcileCommand(parent context.Context, args []string) error { + flags := flag.NewFlagSet("reconcile", flag.ContinueOnError) + apply := flags.Bool("apply", false, "apply changes (default is read-only dry-run)") + grace := flags.Int("grace-seconds", 3600, "minimum object/metadata age, at least 60 seconds") + if err := flags.Parse(args); err != nil { + return err + } + if *grace < 60 || flags.NArg() != 0 { + return errors.New("grace must be >=60 seconds; no positional arguments") + } + uri, err := secretFile("DATABASE_URL_FILE") + if err != nil { + return err + } + cfg, err := pgxpool.ParseConfig(uri) + if err != nil { + return errors.New("invalid database configuration") + } + cfg.MaxConns = 2 + cfg.ConnConfig.ConnectTimeout = 2 * time.Second + cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000" + cfg.ConnConfig.RuntimeParams["lock_timeout"] = "1000" + ctx, cancel := context.WithTimeout(parent, 10*time.Minute) + defer cancel() + db, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return errors.New("database setup failed") + } + defer db.Close() + s3, bucket, err := s3Client() + if err != nil { + return err + } + a := App{db: db, s3: s3, bucket: bucket} + report, err := a.reconcile(ctx, *apply, *grace) + if e := json.NewEncoder(os.Stdout).Encode(report); e != nil { + return e + } + if err != nil { + return errors.New("reconciliation interrupted; inspect dependencies and rerun (no missing inference on network errors)") + } + return nil +} + +func reconcileLoop() error { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + for { + // Each bounded scan closes its resources and emits aggregate statistics. + // The background cleanup uses a one-hour grace period. + err := reconcileCommand(ctx, []string{"--apply"}) + if err != nil { + slog.Warn("reconciliation failed; will retry") + } + timer := time.NewTimer(15 * time.Minute) + select { + case <-ctx.Done(): + timer.Stop() + return nil + case <-timer.C: + } + } +} diff --git a/scripts/bootstrap.py b/scripts/bootstrap.py new file mode 100644 index 00000000..0e31d62e --- /dev/null +++ b/scripts/bootstrap.py @@ -0,0 +1,35 @@ +"""Create local secrets once. Never print values or overwrite existing secrets.""" +from pathlib import Path +import secrets +import shutil + +root = Path(__file__).resolve().parents[1] +folder = root / 'secrets' +folder.mkdir(exist_ok=True) +folder.chmod(0o700) +def put(name, value): + path = folder / name + if not path.exists(): + with path.open('x', encoding='utf-8', newline='\n') as f: + f.write(value + '\n') + # Parent directory is private; Compose mounts individual files for non-root services. + path.chmod(0o644) + return path.read_text(encoding='utf-8').strip() + +pg = put('postgres_password', secrets.token_hex(32)) +vk = put('valkey_password', secrets.token_hex(32)) +put('database_url', f'postgres://messenger:{pg}@db:5432/messenger?sslmode=disable') +put('cache_url', f'redis://:{vk}@valkey:6379/0') +put('cursor_secret', secrets.token_hex(32)) +put('valkey.conf', '\n'.join(['bind 0.0.0.0', 'protected-mode yes', f'requirepass {vk}', + 'dir /data', 'appendonly yes', 'appendfsync always', 'maxmemory 128mb', + 'maxmemory-policy noeviction', 'save 60 1000'])) +if not (root / '.env').exists(): + (root / '.env').write_text((root / '.env.example').read_text(encoding='utf-8').replace('SESSION_STORE=postgres','SESSION_STORE=valkey'),encoding='utf-8') +put('s3_root_user', 'admin_' + secrets.token_hex(8)) +put('s3_root_password', secrets.token_hex(32)) +put('s3_access_key_id', 'api_' + secrets.token_hex(8)) +put('s3_secret_access_key', secrets.token_hex(32)) +for name in ('restart.sh', 'stop-one.sh'): + (root / 'scripts' / name).chmod(0o755) +print('Local .env and secrets ready; existing values preserved.') diff --git a/scripts/linux_tests.py b/scripts/linux_tests.py new file mode 100644 index 00000000..72c3d87a --- /dev/null +++ b/scripts/linux_tests.py @@ -0,0 +1,18 @@ +"""Run the unchanged public make targets with executable Linux action hooks.""" +import argparse +from pathlib import Path +import subprocess + +root = Path(__file__).resolve().parents[1] +p = argparse.ArgumentParser() +p.add_argument('target', choices=['check', 'validate', 'test', 'test-own', 'test-race', 'test-persistence', 'test-failover']) +args = p.parse_args() +command = ['docker', 'run', '--rm', '--network', 'mtusi-lab4_default', + '--mount', 'type=bind,source='+str(root)+',target=/workspace'] +hooks = {'test-persistence': 'scripts/restart.sh', 'test-failover': 'scripts/stop-one.sh'} +if args.target in hooks: + command += ['--mount', 'type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock'] +command += ['mtusi-messenger:lab4-tests', 'make', args.target, 'BASE_URL=http://lb:8080'] +if args.target in hooks: + command += ['ACTION_SCRIPT='+hooks[args.target]] +raise SystemExit(subprocess.call(command, cwd=root)) diff --git a/scripts/manage.py b/scripts/manage.py new file mode 100644 index 00000000..91f52ffd --- /dev/null +++ b/scripts/manage.py @@ -0,0 +1,95 @@ +"""Cross-platform operator commands for the local lab; never delete volumes.""" +import argparse +import datetime as dt +import json +from pathlib import Path +import subprocess +import sys +import time +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] + + +def docker(*args, capture=False, env=None): + result = subprocess.run(['docker', *args], cwd=ROOT, check=True, + text=True, encoding='utf-8', capture_output=capture, env=env) + return result.stdout.strip() if capture else None + + +def replicas(): + ids = docker('compose', 'ps', '-q', 'api', capture=True).split() + if not ids: + return [] + # Only operational fields; never persist Env or secret values. + raw = docker('inspect', '--format', '{{json .Config.Hostname}} {{json .Id}}', *ids, capture=True) + return [dict(zip(('instance', 'id'), (json.loads(x) for x in line.split()))) for line in raw.splitlines()] + + +def ready(count=2, base='http://127.0.0.1:8080'): + deadline = time.monotonic()+90 + observed = set() + while time.monotonic() < deadline: + try: + with urllib.request.urlopen(base+'/health/ready', timeout=2) as response: + observed.add(response.headers['X-Instance-Id']) + if len(observed) >= count: + return + except OSError: + observed.clear() + time.sleep(.2) + raise RuntimeError('expected ready replicas did not appear through LB') + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('action', choices=['start','stop','restart','restore','status','stop-one','rolling']) + p.add_argument('--instance') + args = p.parse_args() + if args.action == 'start': + subprocess.run([sys.executable, '-X', 'utf8', 'scripts/bootstrap.py'], cwd=ROOT, check=True) + docker('compose', 'up', '-d', '--build', '--wait') + ready() + elif args.action == 'stop': + docker('compose', 'down') + elif args.action == 'restart': + docker('compose', 'restart', 'db', 'valkey', 's3', 'api', 'lb') + ready() + elif args.action == 'restore': + docker('compose', 'up', '-d', '--no-deps', '--scale', 'api=2', 'api') + ready() + elif args.action == 'status': + docker('compose', 'ps', '-a') + print(json.dumps(replicas(), indent=2)) + ids = docker('compose','ps','-a','-q',capture=True).split() + template = '[{{json .Id}},{{json .Name}},{{json .Config.Hostname}},{{json .State.Status}},{{json .State.StartedAt}},{{.HostConfig.NanoCpus}},{{.HostConfig.Memory}},{{json .NetworkSettings.Ports}},{{json .Config.Image}}]' + containers = [dict(zip(('id','name','instance','state','started_at','nano_cpus','memory_bytes','ports','image'),json.loads(line))) + for line in docker('inspect','--format',template,*ids,capture=True).splitlines()] + query = "SELECT json_build_object('users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),'messages',(SELECT count(*) FROM messages),'idempotency_keys',(SELECT count(*) FROM message_keys),'database_bytes',pg_database_size(current_database()),'fsync',current_setting('fsync'),'synchronous_commit',current_setting('synchronous_commit'),'full_page_writes',current_setting('full_page_writes'))" + counts = json.loads(docker('compose','exec','-T','db','psql','-U','messenger','-d','messenger','-At','-c',query,capture=True)) + engine = json.loads(docker('info','--format','[{{.NCPU}},{{.MemTotal}},{{json .OSType}},{{json .KernelVersion}},{{json .ServerVersion}},{{json .OperatingSystem}}]',capture=True)) + snapshot = {'timestamp_utc':dt.datetime.now(dt.timezone.utc).isoformat(),'containers':containers,'database':counts, + 'docker_engine':dict(zip(('cpus','memory_bytes','os_type','kernel','version','operating_system'),engine))} + folder = ROOT/'evidence' + folder.mkdir(exist_ok=True) + (folder/'infrastructure.json').write_text(json.dumps(snapshot,indent=2)+'\n',encoding='utf-8') + elif args.action == 'stop-one': + selected = [r for r in replicas() if r['instance']==args.instance] + if len(selected) != 1: + p.error('--instance must match exactly one running API hostname (see status)') + docker('stop', '--time', '9', selected[0]['id']) + else: + original = replicas() + if len(original) != 2: + p.error('rolling replacement requires exactly two running replicas') + for old in original: + docker('compose', 'up', '-d', '--no-deps', '--scale', 'api=3', 'api') + ready(3) + docker('stop', '--time', '9', old['id']) + docker('rm', old['id']) + ready(2) + print(json.dumps({'before':original, 'after':replicas()}, indent=2)) + + +if __name__ == '__main__': + main() diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..74685a00 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +mkdir -p evidence +ids=$(docker compose ps -q db valkey s3 api lb) +docker inspect --format '{{.Id}} {{index .Config.Labels "com.docker.compose.service"}} {{.State.StartedAt}} {{.State.Status}}' $ids > evidence/restart-before.txt +docker compose restart db valkey s3 api lb +docker inspect --format '{{.Id}} {{index .Config.Labels "com.docker.compose.service"}} {{.State.StartedAt}} {{.State.Status}}' $ids > evidence/restart-after.txt diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..6bd90706 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}" +for id in $(docker compose ps -q api); do + hostname=$(docker inspect --format '{{.Config.Hostname}}' "$id") + if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then + mkdir -p evidence + docker inspect --format '{{.Id}} {{.State.Status}} {{.State.StartedAt}}' "$id" > evidence/stopped-before.txt + docker stop --time 9 "$id" > /dev/null + docker inspect --format '{{.Id}} {{.State.Status}} {{.State.FinishedAt}} {{.State.ExitCode}}' "$id" > evidence/stopped-after.txt + exit 0 + fi +done +echo 'Target is not a running API container' >&2 +exit 1 diff --git a/scripts/summarize.py b/scripts/summarize.py new file mode 100644 index 00000000..739a8440 --- /dev/null +++ b/scripts/summarize.py @@ -0,0 +1,47 @@ +"""Render only measured evidence; never turn an unrun check into PASS.""" +import json +from pathlib import Path + +ROOT=Path(__file__).resolve().parents[1] + + +def main(): + folder=ROOT/'evidence' + def read(name): + p=folder/name + return json.loads(p.read_text(encoding='utf-8')) if p.exists() else None + verification=read('verification.json') or {} + lines=['# Фактические результаты lab4','', + 'Полный прогон завершён: **'+('да' if verification.get('complete') else 'нет')+'**.', + 'Контракт и публичные тесты неизменны: '+str(verification.get('protected_unchanged',False))+'.','', + '| Проверка | Exit code | Время, с |','| --- | --- | --- |'] + lines += ['| '+c['name']+' | '+str(c['exit_code'])+' | '+str(c['seconds'])+' |' for c in verification.get('checks',[])] + if verification.get('failure'):lines+=['','Остановка: '+verification['failure']] + if verification.get('pending_revalidation'): + lines+=['','Ожидает полного повторного прогона: настройка на пять загрузок на реплику и десять успешных параллельных запросов. Таблица выше относится к предыдущему прогону.'] + memory=read('upload-memory.json') + if memory: + lines+=['','## 10 одновременно стартующих uploads','', + '| Bytes | Успех | 503 | RPS успешных | p95, мс | Σ cgroup peak, MiB |', + '| --- | --- | --- | --- | --- | --- |'] + for c in memory['cases']: + lines.append('| {} | {} | {} | {:.2f} | {:.2f} | {:.2f} |'.format(c['file_bytes'],c['success'],c['backpressure_503'],c['successful_rps'],c['p95_seconds']*1000,c['sum_cgroup_peaks_bytes']/1048576)) + lines+=['','Сумма отдельных kernel peaks — верхняя оценка одновременного общего пика. Startup включён.'] + research=read('research.json') + if research: + lines+=['','## Согласованность DB/S3','', + '| Этап | Orphan | Missing | Удалено | Отмечено | Восстановлено |', + '| --- | --- | --- | --- | --- | --- |'] + for name in ('dry_run','apply','repeat_apply','recovery'): + c=research[name] + lines.append('| {} | {} | {} | {} | {} | {} |'.format(name,c['old_orphans'],c['missing'],c['deleted'],c['marked_unavailable'],c['cleared_unavailable'])) + lines+=['','| Добавлено объектов | Объектов всего | Metadata rows | HEAD requests | Время обхода, мс (3 повтора) |', + '| --- | --- | --- | --- | --- |'] + for case in research['scan_cost']: + runs=case['runs'];c=runs[0] + lines.append('| {} | {} | {} | {} | {} |'.format(case['added_objects'],c['objects_scanned'],c['metadata_scanned'],c['head_requests'],', '.join(str(x['elapsed_ms']) for x in runs))) + lines+=['','Каждый PASS опирается на журнал соответствующей команды. Отсутствующие результаты не считаются выполненными.'] + (folder/'RESULTS.md').write_text('\n'.join(lines)+'\n',encoding='utf-8') + + +if __name__=='__main__':main() diff --git a/scripts/verify.py b/scripts/verify.py new file mode 100644 index 00000000..161da848 --- /dev/null +++ b/scripts/verify.py @@ -0,0 +1,104 @@ +"""Complete, sequential verification on a disposable local Compose lab.""" +import argparse +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time + +ROOT=Path(__file__).resolve().parents[1] + + +def protected(): + return {str(p.relative_to(ROOT)).replace('\\','/'):hashlib.sha256(p.read_bytes()).hexdigest() + for folder in ('contracts','tests') for p in (ROOT/folder).rglob('*') + if p.is_file() and '__pycache__' not in p.parts} + + +def main(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('--static-only',action='store_true') + p.add_argument('--resume-integration',action='store_true',help='reuse successful local checks, rerun build and every integration check') + args=p.parse_args() + # Compose publishes IPv4 loopback. Avoid Windows localhost IPv6 fallback + # and keep public/private child clients on the same operator-supplied URL. + os.environ.setdefault('BASE_URL', 'http://127.0.0.1:8080') + evidence=ROOT/'evidence';evidence.mkdir(exist_ok=True) + result={'started_utc':dt.datetime.now(dt.timezone.utc).isoformat(),'complete':False,'checks':[]} + if args.resume_integration: + previous=json.loads((evidence/'verification.json').read_text(encoding='utf-8')) + names={'contract','go-test','go-vet','student-unit','go-vuln','go-race'} + successful={c['name']:c for c in previous['checks'] if c['name'] in names and c['exit_code']==0} + if set(successful)!=names: + raise RuntimeError('resume requires all local and race checks to have passed') + cutoff=dt.datetime.fromisoformat(previous.get('local_checks_from_utc',previous['started_utc'])).timestamp() + source=list(ROOT.glob('*.go'))+list((ROOT/'migrations').glob('*.sql'))+[ROOT/'go.mod',ROOT/'go.sum',ROOT/'Dockerfile'] + if any(path.stat().st_mtime>cutoff for path in source): + raise RuntimeError('application sources changed; run the full verifier') + result['checks']=[successful[name] for name in ('contract','go-test','go-vet','student-unit','go-vuln','go-race')] + result['local_checks_from_utc']=previous.get('local_checks_from_utc',previous['started_utc']) + manifest=evidence/'protected-files.json' + original=json.loads(manifest.read_text(encoding='utf-8')) if manifest.exists() else protected() + if protected()!=original: + raise RuntimeError('protected files differ from the original SHA-256 manifest') + def persist(): + result['protected_unchanged']=protected()==original + (evidence/'verification.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8') + subprocess.run([sys.executable,'-X','utf8','scripts/summarize.py'],cwd=ROOT,check=True) + def run(name,command,timeout=1200): + print('Running '+name,flush=True) + start=time.monotonic() + with (evidence/(name+'.txt')).open('w',encoding='utf-8') as output: + completed=subprocess.run(command,cwd=ROOT,stdout=output,stderr=subprocess.STDOUT, + encoding='utf-8',timeout=timeout) + result['checks'].append({'name':name,'command':command,'exit_code':completed.returncode,'seconds':round(time.monotonic()-start,3)}) + persist() + if completed.returncode: + raise RuntimeError(name+' failed; see evidence/'+name+'.txt') + py=[sys.executable,'-X','utf8'] + try: + if not args.resume_integration: + run('contract',py+['scripts/check_contract.py']) + run('go-test',['go','test','./...']) + run('go-vet',['go','vet','./...']) + run('student-unit',py+['student-tests/unit.py']) + run('go-vuln',['go','run','golang.org/x/vuln/cmd/govulncheck@v1.1.4','./...']) + if args.static_only: + result['static_complete']=True + return + run('bootstrap',py+['scripts/bootstrap.py']) + run('compose-config',['docker','compose','config','--quiet']) + run('start',py+['scripts/manage.py','start'],3600) + run('build-tests',['docker','build','-f','Dockerfile.tests','-t','mtusi-messenger:lab4-tests','.'],1800) + run('openapi',py+['scripts/linux_tests.py','validate']) + if not args.resume_integration: + run('go-race',['docker','run','--rm','--mount','type=bind,source='+str(ROOT)+',target=/workspace', + 'mtusi-messenger:lab4-tests','go','test','-race','./...'],1200) + run('smoke',py+['tests/smoke.py']) + run('attachments',py+['student-tests/attachments.py']) + run('persistence',py+['scripts/linux_tests.py','test-persistence']) + run('ready-before-failover',py+['scripts/manage.py','restore']) + for i in range(2): + run('failover-'+str(i+1),py+['scripts/linux_tests.py','test-failover']) + run('restore-'+str(i+1),py+['scripts/manage.py','restore']) + run('failures',py+['student-tests/failures.py']) + run('memory',py+['student-tests/memory.py']) + run('research',py+['student-tests/research.py'],1800) + run('load',py+['tests/load.py','--duration','30','--concurrency','4','--output','evidence/load.json']) + run('infrastructure',py+['scripts/manage.py','status']) + result['complete']=True + except (RuntimeError,subprocess.TimeoutExpired,FileNotFoundError) as exc: + result['failure']=str(exc) + print(str(exc),file=sys.stderr) + raise SystemExit(1) + finally: + persist() + if not result['protected_unchanged']: + raise RuntimeError('protected files changed during verification') + + +if __name__=='__main__': + main() diff --git a/store.go b/store.go new file mode 100644 index 00000000..92dc4a9b --- /dev/null +++ b/store.go @@ -0,0 +1,223 @@ +package main + +import ( + "context" + "crypto/sha256" + "embed" + "encoding/hex" + "errors" + "fmt" + "sort" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" +) + +//go:embed migrations/*.sql +var migrations embed.FS + +func migrate(ctx context.Context, db *pgxpool.Pool) error { + conn, err := db.Acquire(ctx) + if err != nil { + return err + } + defer conn.Release() + if _, err = conn.Exec(ctx, "SELECT pg_advisory_lock(202602)"); err != nil { + return err + } + defer conn.Exec(context.Background(), "SELECT pg_advisory_unlock(202602)") + if _, err = conn.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())"); err != nil { + return err + } + entries, err := migrations.ReadDir("migrations") + if err != nil { + return err + } + sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() }) + for _, entry := range entries { + raw, err := migrations.ReadFile("migrations/" + entry.Name()) + if err != nil { + return err + } + sum := sha256.Sum256(raw) + checksum := hex.EncodeToString(sum[:]) + var previous string + err = conn.QueryRow(ctx, "SELECT checksum FROM schema_migrations WHERE version=$1", entry.Name()).Scan(&previous) + if err == nil { + if previous != checksum { + return fmt.Errorf("migration checksum mismatch: %s", entry.Name()) + } + continue + } + if !errors.Is(err, pgx.ErrNoRows) { + return err + } + tx, err := conn.Begin(ctx) + if err != nil { + return err + } + if _, err = tx.Exec(ctx, string(raw)); err == nil { + _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version,checksum) VALUES($1,$2)", entry.Name(), checksum) + } + if err != nil { + tx.Rollback(ctx) + return err + } + if err = tx.Commit(ctx); err != nil { + return err + } + } + return nil +} + +func dbError(err error) error { + if err == nil { + return nil + } + if errors.Is(err, pgx.ErrNoRows) { + return missing() + } + var pe *pgconn.PgError + if errors.As(err, &pe) { + switch pe.Code { + case "23505": + return apiError{409, "conflict", "Username already exists"} + case "23503", "23514", "22P02", "22021": + return invalid() + } + } + return unavailable() +} +func stamp(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000000Z") } + +// pgx BytesScanner preserves every validated UTF-8 code point, including NUL. +type utf8String struct{ dst *string } + +func (s utf8String) ScanBytes(value []byte) error { + *s.dst = string(value) + return nil +} + +func scanUser(row pgx.Row) (User, error) { + var u User + var t time.Time + err := row.Scan(&u.ID, &u.Username, utf8String{&u.DisplayName}, &t) + u.CreatedAt = stamp(t) + return u, dbError(err) +} +func (a *App) user(ctx context.Context, id string) (User, error) { + return scanUser(a.db.QueryRow(ctx, "SELECT id::text,username,display_name,created_at FROM users WHERE id=$1", id)) +} + +func (a *App) createChat(ctx context.Context, title string, ids []string) (Chat, error) { + c := Chat{ID: uuid(), Title: title, MemberIDs: ids} + var t time.Time + tx, err := a.db.Begin(ctx) + if err != nil { + return c, unavailable() + } + defer tx.Rollback(ctx) + err = tx.QueryRow(ctx, "INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at", c.ID, []byte(title)).Scan(&t) + if err != nil { + return c, dbError(err) + } + // FK failure on any participant rolls back the chat and earlier participants. + for _, id := range ids { + if _, err = tx.Exec(ctx, "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", c.ID, id); err != nil { + return c, dbError(err) + } + } + if err = tx.Commit(ctx); err != nil { + return c, unavailable() + } + c.CreatedAt = stamp(t) + return c, nil +} +func (a *App) chat(ctx context.Context, id, user string) (Chat, error) { + c := Chat{} + var t time.Time + err := a.db.QueryRow(ctx, `SELECT c.id::text,c.title,c.created_at, + ARRAY(SELECT user_id::text FROM chat_members WHERE chat_id=c.id ORDER BY user_id) + FROM chats c WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2)`, id, user).Scan(&c.ID, utf8String{&c.Title}, &t, &c.MemberIDs) + c.CreatedAt = stamp(t) + return c, dbError(err) +} +func boundary(c cursor) (time.Time, string, error) { + if c.ID == "" { + return time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC), "00000000-0000-0000-0000-000000000000", nil + } + t, err := time.Parse(time.RFC3339Nano, c.Time) + if err != nil { + return t, "", invalid() + } + id, err := normalizeID(c.ID) + return t, id, err +} +func (a *App) history(ctx context.Context, id string, limit int, c cursor, scope string) (Page[Message], error) { + result := Page[Message]{Items: []Message{}} + t, last, err := boundary(c) + if err != nil { + return result, err + } + rows, err := a.db.Query(ctx, `SELECT id::text,chat_id::text,sender_id::text,text,created_at,ARRAY(SELECT unnest(attachment_ids)::text) FROM messages + WHERE chat_id=$1 AND (created_at,id)>($2,$3) ORDER BY messages.created_at,messages.id LIMIT $4`, id, t, last, limit+1) + if err != nil { + return result, unavailable() + } + defer rows.Close() + for rows.Next() { + var m Message + var created time.Time + if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, utf8String{&m.Text}, &created, &m.AttachmentIDs); err != nil { + return result, unavailable() + } + m.CreatedAt = stamp(created) + result.Items = append(result.Items, m) + } + if rows.Err() != nil { + return result, unavailable() + } + if len(result.Items) > limit { + result.Items = result.Items[:limit] + m := result.Items[limit-1] + next := a.encodeCursor(scope, m.CreatedAt, m.ID) + result.NextCursor = &next + } + return result, nil +} +func (a *App) listChats(ctx context.Context, user string, limit int, c cursor, scope string) (Page[Chat], error) { + result := Page[Chat]{Items: []Chat{}} + t, last, err := boundary(c) + if err != nil { + return result, err + } + rows, err := a.db.Query(ctx, `SELECT c.id::text,c.title,c.created_at, + ARRAY(SELECT user_id::text FROM chat_members WHERE chat_id=c.id ORDER BY user_id) + FROM chats c JOIN chat_members own ON own.chat_id=c.id AND own.user_id=$1 + WHERE (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, user, t, last, limit+1) + if err != nil { + return result, unavailable() + } + defer rows.Close() + for rows.Next() { + var chat Chat + var created time.Time + if err = rows.Scan(&chat.ID, utf8String{&chat.Title}, &created, &chat.MemberIDs); err != nil { + return result, unavailable() + } + chat.CreatedAt = stamp(created) + result.Items = append(result.Items, chat) + } + if rows.Err() != nil { + return result, unavailable() + } + if len(result.Items) > limit { + result.Items = result.Items[:limit] + v := result.Items[limit-1] + next := a.encodeCursor(scope, v.CreatedAt, v.ID) + result.NextCursor = &next + } + return result, nil +} diff --git a/student-tests/attachments.py b/student-tests/attachments.py new file mode 100644 index 00000000..cb9197e1 --- /dev/null +++ b/student-tests/attachments.py @@ -0,0 +1,84 @@ +"""Black-box validation of attachment security and message compatibility.""" +import concurrent.futures +import hashlib +import json +import struct +import urllib.parse +import uuid +import zlib +from common import ROOT, Client, check, save + + +def chunk(kind, data): + return struct.pack('!I',len(data))+kind+data+struct.pack('!I',zlib.crc32(kind+data)&0xffffffff) + + +def png(width=32, height=32): + return (b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!IIBBBBB',width,height,8,2,0,0,0))+ + chunk(b'IDAT',zlib.compress((b'\0'+bytes([43,100,201])*width)*height))+chunk(b'IEND',b'')) + + +def main(): + c=Client(timeout=40) + alice,bob,eve,chat=c.bootstrap() + path='/api/v1/chats/'+chat['id'] + payload=(ROOT/'tests/fixtures/sample.png').read_bytes() + passed=[] + def upload(data, status, name='image.png', mime='image/png', actor=alice): + result=c.call('POST',path+'/attachments?filename='+urllib.parse.quote(name,safe=''),status, + actor=actor,raw=data,headers={'Content-Type':mime},schema='Attachment' if status==201 else None) + return result + upload(b'x'*(10485760+1),413);passed.append('byte limit before decode') + upload(b'not an image',415) + upload(payload[:40],415) + upload(payload,415,mime='image/jpeg') + upload(payload,415,mime='text/plain') + upload(b'',415);passed.append('corrupt, empty, MIME spoof') + # Valid header with impossible dimensions: rejection precedes allocation. + huge=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!IIBBBBB',40000001,1,8,2,0,0,0)) + upload(huge,413);passed.append('pixel limit before full decode') + for name in ('../a.png','a/b.png','a\\b.png','x\x00.png','x\n.png','x\x7f.png',' '*4,'a'*256): + upload(payload,400,name=name) + passed.append('unsafe filename') + upload(payload,404,actor=eve) + c.call('POST',path+'/attachments?filename=a.png',401,raw=payload,headers={'Content-Type':'image/png'}) + att=upload(payload,201,name='Фотография 😀.png')['json'] + check(att['sha256']==hashlib.sha256(payload).hexdigest(),'bad original hash') + for suffix in ('','/content'): + c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=eve) + c.call('GET','/api/v1/attachments/'+str(uuid.uuid4())+suffix,404,actor=alice) + foreign=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'other','member_ids':[alice['id'],bob['id']]},schema='Chat')['json'] + c.call('POST','/api/v1/chats/'+foreign['id']+'/messages',404,actor=alice, + body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex}) + passed.append('foreign attachment and chat ACL') + for body in ({'text':'','attachment_ids':[att['id'],att['id']]}, + {'text':'','attachment_ids':None}, {'text':'x','attachment_ids':['not-uuid']}, + {'text':'x','sender_id':eve['id']}, {'text':' '}): + c.call('POST',path+'/messages',400,actor=alice,body=body,headers={'Idempotency-Key':uuid.uuid4().hex}) + key=uuid.uuid4().hex + first=c.message(alice,chat,'',key,[att['id']])['json'] + repeat=c.message(alice,chat,'',key,[att['id']])['json'] + check(first==repeat,'attachment message replay changed') + c.call('POST',path+'/messages',409,actor=alice,body={'text':'changed','attachment_ids':[att['id']]},headers={'Idempotency-Key':key}) + key=uuid.uuid4().hex + plain=c.message(alice,chat,'text only',key)['json'] + check(plain==c.message(alice,chat,'text only',key,[])['json'],'omitted != empty attachment_ids') + key=uuid.uuid4().hex + with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool: + messages=list(pool.map(lambda _:Client().message(alice,chat,'concurrent',key,[att['id']])['json'],range(12))) + check(len({m['id'] for m in messages})==1,'concurrent idempotency created duplicates') + response=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob) + check(response['bytes']==payload,'download changed bytes') + check(response['headers'].get_content_type()=='image/png','wrong download MIME') + c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',404,actor=alice) + passed.append('attachment-only, text-only, replay, concurrent replay, exact download') + jpeg=(ROOT/'student-tests/fixtures/sample.jpg').read_bytes() + item=upload(jpeg,201,name='valid.jpg',mime='image/jpeg')['json'] + check(c.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=bob)['bytes']==jpeg,'JPEG changed') + passed.append('real JPEG exact download') + save('attachments.json',{'complete':True,'passed':passed}) + print('PASS attachment validation, ACL and compatibility') + + +if __name__=='__main__': + main() diff --git a/student-tests/common.py b/student-tests/common.py new file mode 100644 index 00000000..9358a0b4 --- /dev/null +++ b/student-tests/common.py @@ -0,0 +1,79 @@ +"""Shared operator/test helpers. Never print credentials or HTTP bodies.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT/'tests')) +from client import Client as PublicClient, check + + +class Client(PublicClient): + """Use the published IPv4 loopback by default; respect explicit targets.""" + def __init__(self, base_url=None, ca_file=None, timeout=10): + super().__init__(base_url or os.environ.get('BASE_URL') or 'http://127.0.0.1:8080', + ca_file=ca_file, timeout=timeout) + + +def command(args, *, capture=True, timeout=600, input=None): + result = subprocess.run(args, cwd=ROOT, input=input, text=True, + encoding='utf-8', errors='replace', capture_output=capture, + timeout=timeout) + if result.returncode: + # Child output may contain environment-specific details. Full command + # does not contain secrets, but do not echo arbitrary child stderr. + raise RuntimeError('command failed: '+str(args[0])+' (exit '+str(result.returncode)+')') + return result.stdout.strip() if capture else None + + +def compose(*args, **kwargs): + return command(['docker', 'compose', *args], **kwargs) + + +def sql(query): + return compose('exec', '-T', 'db', 'psql', '-X', '-v', 'ON_ERROR_STOP=1', + '-U', 'messenger', '-d', 'messenger', '-At', '-c', query) + + +def mc(script): + setup = ('set -eu\nmc alias set local http://s3:9000 ' + '"$(cat /run/secrets/s3_root_user)" ' + '"$(cat /run/secrets/s3_root_password)" >/dev/null\n') + return compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/bin/sh', + 's3-init', '-c', setup+script) + + +def reconcile(apply=False, grace=60): + args = ['exec', '-T', 'api', '/messenger', 'reconcile', '--grace-seconds', str(grace)] + if apply: + args.append('--apply') + report = json.loads(compose(*args)) + check(report['complete'], 'incomplete reconciler report') + return report + + +def wait_ready(base=None, seconds=90, count=1): + deadline = time.monotonic()+seconds + client=Client(base, timeout=2) + observed=set() + last_error=None + while time.monotonic()=count:return + except (OSError,AssertionError) as exc: + last_error=type(exc).__name__ + observed.clear() + time.sleep(.1) + raise RuntimeError('stack did not become ready: expected '+str(count)+ + ' distinct replicas, observed '+str(len(observed))+ + '; last probe '+(last_error or 'HTTP 200')) + + +def save(name, data): + (ROOT/'evidence').mkdir(exist_ok=True) + (ROOT/'evidence'/name).write_text(json.dumps(data, ensure_ascii=False, indent=2)+'\n', encoding='utf-8') diff --git a/student-tests/failures.py b/student-tests/failures.py new file mode 100644 index 00000000..7423a554 --- /dev/null +++ b/student-tests/failures.py @@ -0,0 +1,101 @@ +"""Sequential infrastructure faults; restores every stopped service in finally.""" +import http.client +import json +import time +import urllib.parse +from common import ROOT, Client, check, command, compose, mc, sql, wait_ready, save + + +def inside(program, data=None): + return command(['docker','run','--rm','-i','--network','mtusi-lab4_default', + '--mount','type=bind,source='+str(ROOT)+',target=/workspace', + 'mtusi-messenger:lab4-tests','python','-X','utf8','-c',program], + input=json.dumps(data) if data is not None else '') + + +def main(): + c=Client(timeout=40) + alice,bob,eve,chat=c.bootstrap() + att,content=c.attachment(alice,chat) + results=[] + key='original/'+att['id'] + status=inside("import urllib.request,urllib.error;\ntry:\n r=urllib.request.urlopen('http://s3:9000/messenger-attachments/"+key+"');print(r.status)\nexcept urllib.error.HTTPError as e: print(e.code)") + check(status=='403','anonymous S3 access was not denied') + results.append('private bucket anonymous GET: 403') + guard=inside("""import urllib.request,urllib.error +cases=[('/messenger-attachments/original/guard-test',{'X-Amz-Content-Sha256':'STREAMING-UNSIGNED-PAYLOAD-TRAILER'},'PUT'), + ('/minio/storage/v63/rmpl',{},'POST'),('/messenger-attachments/x?select&select-type=2',{},'POST'), + ('/messenger-attachments/x',{'X-Minio-Source-Replication-Request':'true'},'PUT')] +for path,headers,method in cases: + try: + response=urllib.request.urlopen(urllib.request.Request('http://s3:9000'+path,data=b'',headers=headers,method=method)) + assert response.status==403 + except urllib.error.HTTPError as e: assert e.code==403 +print('PASS')""") + check(guard=='PASS','MinIO network guard failed') + results.append('unsigned trailers, storage REST, S3 Select and replication headers blocked at private proxy') + # API identity can use only this bucket/prefix, never administrative APIs. + denied=mc('mc alias set app http://s3:9000 "$(cat /run/secrets/s3_access_key_id)" "$(cat /run/secrets/s3_secret_access_key)" >/dev/null\n' + 'if mc admin user list app >/dev/null 2>&1; then exit 10; fi\n' + 'if mc mb app/forbidden-bucket >/dev/null 2>&1; then exit 11; fi\n' + 'if printf x | mc pipe app/messenger-attachments/outside-prefix >/dev/null 2>&1; then exit 12; fi\n' + 'echo denied') + check(denied=='denied','S3 API policy too broad') + results.append('API account cannot administer, create bucket or write outside original/') + # Check bootstrap twice without replacing secrets or losing bytes. + compose('run','--rm','--no-deps','-T','s3-init') + compose('run','--rm','--no-deps','-T','s3-init') + check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==content,'bootstrap lost original') + results.append('idempotent bootstrap preserves data and credentials') + try: + compose('stop','s3') + # Readiness removes both replicas from LB, so query internal API to + # distinguish the application JSON error from the LB transport error. + program='''import sys,json +sys.path.insert(0,'tests') +from client import Client +x=json.load(sys.stdin);c=Client('http://api:8080',timeout=40) +c.call('GET','/health/live',schema='Health') +c.call('GET','/health/ready',503) +c.call('POST','/api/v1/chats/'+x['chat']+'/attachments?filename=a.png',503,actor=x['actor'],raw=open('tests/fixtures/sample.png','rb').read(),headers={'Content-Type':'image/png'}) +c.call('GET','/api/v1/attachments/'+x['attachment']+'/content',503,actor=x['actor']) +print('PASS')''' + check(inside(program,{'actor':alice,'chat':chat['id'],'attachment':att['id']})=='PASS','S3 outage error mapping') + finally: + compose('start','s3');wait_ready() + check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==content,'S3 restart lost data') + results.append('S3 outage: live 200, ready/upload/content 503, restart retains bytes') + response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=uploader.png',201, + actor=alice,raw=content,headers={'Content-Type':'image/png'},schema='Attachment') + uploader=response['headers']['X-Instance-Id'];uploaded=response['json'] + ids=compose('ps','-q','api').split() + selected=[] + for container in ids: + hostname=command(['docker','inspect','--format','{{.Config.Hostname}}',container]) + if hostname==uploader:selected.append(container) + check(len(selected)==1,'uploading replica did not map to exactly one container') + try: + command(['docker','stop','--time','9',selected[0]]) + wait_ready() + download=c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content',actor=bob) + check(download['bytes']==content,'replica failover changed original') + check(download['headers']['X-Instance-Id']!=uploader,'download still used stopped uploader') + finally: + compose('up','-d','--no-deps','--scale','api=2','api');wait_ready() + results.append('exact uploading container stopped; another replica returned identical original with old session') + # An interrupted body must not reach PUT or metadata insertion. + before=sql('SELECT count(*) FROM attachments') + url=urllib.parse.urlsplit(c.base) + conn=http.client.HTTPConnection(url.hostname,url.port or 80,timeout=5) + conn.putrequest('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=abort.png') + conn.putheader('Authorization','Bearer '+alice['token']) + conn.putheader('Content-Type','image/png');conn.putheader('Content-Length',str(len(content)+1000));conn.endheaders() + conn.send(content[:30]);conn.close();time.sleep(.5) + check(sql('SELECT count(*) FROM attachments')==before,'aborted upload created metadata') + results.append('interrupted body creates no metadata; dependency recovers') + save('failures.json',{'complete':True,'passed':results}) + print('PASS private bucket, least privilege, bootstrap, S3 outage, aborted body') + + +if __name__=='__main__': + main() diff --git a/student-tests/fixtures/sample.jpg b/student-tests/fixtures/sample.jpg new file mode 100644 index 00000000..d99350c9 Binary files /dev/null and b/student-tests/fixtures/sample.jpg differ diff --git a/student-tests/kdf-bench.go.txt b/student-tests/kdf-bench.go.txt new file mode 100644 index 00000000..ac4cfd90 --- /dev/null +++ b/student-tests/kdf-bench.go.txt @@ -0,0 +1,23 @@ +package main + +import ( + "encoding/json" + "os" + "runtime" + "runtime/debug" + "time" + "golang.org/x/crypto/argon2" +) + +func main() { + samples:=[]float64{} + for i:=0;i<5;i++ { + start:=time.Now() + hash:=argon2.IDKey([]byte("synthetic-diagnostic-password"),[]byte("synthetic-salt12"),3,64*1024,1,32) + runtime.KeepAlive(hash) + samples=append(samples,float64(time.Since(start).Microseconds())/1000) + debug.FreeOSMemory() + } + stats,_:=os.ReadFile("/sys/fs/cgroup/cpu.stat") + json.NewEncoder(os.Stdout).Encode(map[string]any{"kdf_ms":samples,"cpu_stat":string(stats),"gomaxprocs":runtime.GOMAXPROCS(0)}) +} diff --git a/student-tests/memory.py b/student-tests/memory.py new file mode 100644 index 00000000..1f5bb736 --- /dev/null +++ b/student-tests/memory.py @@ -0,0 +1,89 @@ +"""Ten simultaneous uploads, two file sizes; sampled cgroup memory and CPU.""" +import concurrent.futures +import json +import math +import random +import re +import statistics +import struct +import threading +import time +import zlib +from common import Client, check, command, compose, save, wait_ready +from attachments import chunk + + +def image(side): + rng=random.Random(104729+side) + pixels=b''.join(b'\0'+rng.randbytes(side*3) for _ in range(side)) + return (b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!IIBBBBB',side,side,8,2,0,0,0))+ + chunk(b'IDAT',zlib.compress(pixels,1))+chunk(b'IEND',b'')) + + +def bytes_value(value): + number,unit=re.fullmatch(r'([0-9.]+)\s*([A-Za-z]+)',value.strip()).groups() + return round(float(number)*{'B':1,'KiB':1024,'MiB':1024**2,'GiB':1024**3,'kB':1000,'MB':1000**2,'GB':1000**3}[unit]) + + +def main(): + c=Client(timeout=40);alice,bob,eve,chat=c.bootstrap() + ids=compose('ps','-q','api').split() + check(len(ids)>=2,'need two API containers') + cases=[] + for side in (256,1536): + compose('up','-d','--no-deps','--force-recreate','--scale','api=2','api');wait_ready(count=2) + ids=compose('ps','-q','api').split() + baseline_cgroup=[json.loads(command(['docker','exec',i,'/messenger','memory-snapshot'])) for i in ids] + payload=image(side);samples=[];sampling_errors=[];stop=threading.Event();timing={} + barrier=threading.Barrier(11,action=lambda:timing.update(start=time.monotonic())) + def sample(): + while not stop.is_set(): + try: + raw=command(['docker','stats','--no-stream','--format','{{json .}}',*ids],timeout=20) + except Exception as exc: + sampling_errors.append(type(exc).__name__);return + rows=[json.loads(line) for line in raw.splitlines()] + samples.append({'t':time.monotonic(),'total_bytes':sum(bytes_value(r['MemUsage'].split('/')[0]) for r in rows), + 'containers':[{k:r[k] for k in ('Name','MemUsage','CPUPerc')} for r in rows]}) + stop.wait(.1) + monitor=threading.Thread(target=sample,daemon=True);monitor.start() + while not samples: + if sampling_errors:raise RuntimeError('Docker memory sampler failed') + time.sleep(.05) + def upload(_): + client=Client(timeout=40);barrier.wait(timeout=90) + start=time.monotonic() + result=client.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=memory.png',[201,503], + actor=alice,raw=payload,headers={'Content-Type':'image/png'}) + return result['status'],time.monotonic()-start + try: + with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool: + pending=[pool.submit(upload,i) for i in range(10)] + barrier.wait(timeout=90);results=[f.result() for f in pending] + elapsed=time.monotonic()-timing['start'] + # Keep sampling after the burst to catch the next Docker sample. + time.sleep(2) + finally: + stop.set();monitor.join(timeout=20) + successes=[latency for status,latency in results if status==201] + check(not sampling_errors,'Docker memory sampling failed') + peaks=[json.loads(command(['docker','exec',i,'/messenger','memory-snapshot'])) for i in ids] + check(len(successes)==10,'all ten simultaneous uploads must complete successfully') + ordered=sorted(successes) + percentile=lambda q:ordered[min(len(ordered)-1,max(0,math.ceil(len(ordered)*q)-1))] + cases.append({'file_bytes':len(payload),'pixels':side*side,'concurrency':10,'requests':10, + 'success':len(successes),'backpressure_503':len(results)-len(successes), + 'error_fraction':(len(results)-len(successes))/len(results), + 'successful_rps':len(successes)/elapsed,'duration_seconds':elapsed, + 'p50_seconds':percentile(.5),'p95_seconds':percentile(.95),'p99_seconds':percentile(.99), + 'baseline_bytes':samples[0]['total_bytes'],'sampled_peak_bytes':max(x['total_bytes'] for x in samples), + 'baseline_cgroups':baseline_cgroup,'peak_cgroups':peaks, + 'sum_cgroup_peaks_bytes':sum(x['memory.peak'] for x in peaks), + 'samples':samples}) + save('upload-memory.json',{'complete':True,'method':'10 simultaneous clients, no retries; docker stats CPU/RAM plus kernel cgroup-v2 memory.peak; API cgroups recreated per case. Sum of individual peaks is an upper bound on simultaneous total peak.', + 'cases':cases}) + print('PASS 10-client memory experiment at two sizes (see upload-memory.json)') + + +if __name__=='__main__': + main() diff --git a/student-tests/readiness_test.py b/student-tests/readiness_test.py new file mode 100644 index 00000000..b90e405d --- /dev/null +++ b/student-tests/readiness_test.py @@ -0,0 +1,46 @@ +"""Regression checks for private readiness probes; public client is unchanged.""" +import os +import unittest +from unittest.mock import patch + +from common import Client, wait_ready + + +class ReadinessTests(unittest.TestCase): + def test_local_default_matches_published_address(self): + with patch.dict(os.environ, {}, clear=True): + self.assertEqual(Client().base, 'http://127.0.0.1:8080') + + def test_custom_environment_and_direct_backend_are_preserved(self): + with patch.dict(os.environ, {'BASE_URL': 'http://test.example:8080/'}): + self.assertEqual(Client().base, 'http://test.example:8080') + self.assertEqual(Client('http://api:8080').base, 'http://api:8080') + + def test_one_ready_replica_does_not_satisfy_two(self): + with patch('common.Client') as client, patch('common.time.sleep'): + client.return_value.call.side_effect = [ + {'headers': {'X-Instance-Id': name}} + for name in ('one', 'one', 'two')] + wait_ready(count=2) + self.assertEqual(client.return_value.call.call_count, 3) + + def test_unavailable_interval_invalidates_old_observations(self): + with patch('common.Client') as client, patch('common.time.sleep'): + client.return_value.call.side_effect = [ + {'headers': {'X-Instance-Id': 'old'}}, + AssertionError('not ready'), + {'headers': {'X-Instance-Id': 'new-one'}}, + {'headers': {'X-Instance-Id': 'new-two'}}] + wait_ready(count=2) + self.assertEqual(client.return_value.call.call_count, 4) + + def test_timeout_reports_missing_replica_count(self): + with patch('common.Client') as client, patch('common.time.sleep'), \ + patch('common.time.monotonic', side_effect=[0, 0, 2]): + client.return_value.call.return_value = {'headers': {'X-Instance-Id': 'one'}} + with self.assertRaisesRegex(RuntimeError, 'expected 2 distinct replicas, observed 1'): + wait_ready(count=2, seconds=1) + + +if __name__ == '__main__': + unittest.main() diff --git a/student-tests/research.py b/student-tests/research.py new file mode 100644 index 00000000..94d64d0e --- /dev/null +++ b/student-tests/research.py @@ -0,0 +1,104 @@ +"""Track 2: injected PostgreSQL/S3 faults, dry-run, repeatability and scan cost.""" +import concurrent.futures +import hashlib +import json +import threading +import time +import uuid +from common import ROOT, Client, check, command, compose, mc, sql, reconcile, save + + +def objects(): + raw=mc('mc ls --json --recursive local/messenger-attachments/original/') + # mc lists keys relative to the supplied prefix. + return {'original/'+line['key'].removeprefix('original/') for line in + (json.loads(x) for x in raw.splitlines() if x.strip()) if line.get('type')=='file'} + + +def main(): + c=Client(timeout=40);alice,bob,eve,chat=c.bootstrap() + original=(ROOT/'tests/fixtures/sample.png').read_bytes() + path='/api/v1/chats/'+chat['id']+'/attachments?filename=' + used,_=c.attachment(alice,chat) + missing,_=c.attachment(alice,chat) + c.message(alice,chat,'referenced old attachment',attachments=[used['id'],missing['id']]) + baseline=objects() + marker='fault_'+uuid.uuid4().hex+'.png' + # Fault only our unique synthetic filename. No production test hooks. + sql("CREATE FUNCTION student_reject_attachment() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='"+marker+"' THEN RAISE EXCEPTION 'injected metadata failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER student_reject_attachment BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION student_reject_attachment()") + try: + c.call('POST',path+marker,503,actor=alice,raw=original,headers={'Content-Type':'image/png'}) + finally: + sql('DROP TRIGGER IF EXISTS student_reject_attachment ON attachments; DROP FUNCTION IF EXISTS student_reject_attachment()') + orphaned=objects()-baseline + check(len(orphaned)==1,'injected commit-side failure did not leave exactly one orphan') + old_orphan=next(iter(orphaned)) + check(sql("SELECT count(*) FROM attachments WHERE object_key='"+old_orphan+"'")=='0','orphan has metadata') + print('Waiting 65 seconds for the real S3 LastModified grace (no timestamp forgery).',flush=True) + deadline=time.monotonic()+65 + while time.monotonic()/tmp/fresh; mc cp /tmp/fresh local/messenger-attachments/"+fresh_key+" >/dev/null") + mc('mc rm local/messenger-attachments/original/'+missing['id']+' >/dev/null') + metadata_before=sql('SELECT count(*) FROM attachments') + before=objects() + dry=reconcile(False) + check(dry['old_orphans']>=1 and dry['missing']>=1,'dry-run did not detect both failure directions') + check(objects()==before,'dry-run changed S3') + check(sql("SELECT missing_since IS NULL FROM attachments WHERE id='"+missing['id']+"'")=='t','dry-run changed DB') + apply=reconcile(True) + after=objects() + check(old_orphan not in after,'old orphan not removed') + check(fresh_key in after,'fresh orphan was deleted') + check('original/'+used['id'] in after,'referenced object was deleted') + check(sql('SELECT count(*) FROM attachments')==metadata_before,'missing metadata was deleted') + check(sql("SELECT count(*) FROM message_attachments WHERE attachment_id='"+missing['id']+"'")=='1','message reference was lost') + c.call('GET','/api/v1/attachments/'+missing['id'],503,actor=bob) + c.call('GET','/api/v1/attachments/'+missing['id'],404,actor=eve) + repeat=reconcile(True) + check(repeat['deleted']==0 and repeat['marked_unavailable']==0,'second apply is not idempotent') + # Restore exact bytes from the fixture; only matching SHA-256 clears marker. + # Binary stdin avoids encoding files or credential-bearing process args. + import subprocess + script=('set -eu\nmc alias set local http://s3:9000 "$(cat /run/secrets/s3_root_user)" ' + '"$(cat /run/secrets/s3_root_password)" >/dev/null\n' + 'cat >/tmp/original; mc cp /tmp/original local/messenger-attachments/original/'+missing['id']+' >/dev/null') + subprocess.run(['docker','compose','run','--rm','--no-deps','-T','--entrypoint','/bin/sh','s3-init','-c',script], + cwd=ROOT,input=original,stdout=subprocess.DEVNULL,check=True,timeout=60) + recovered=reconcile(True) + check(recovered['recovered']==1 and recovered['cleared_unavailable']==1,'restore not verified/repaired') + check(c.call('GET','/api/v1/attachments/'+missing['id']+'/content',actor=bob)['bytes']==original,'restored bytes differ') + # Reconciler while legitimate concurrent uploads commit: no live object loss. + barrier=threading.Barrier(4) + def upload(_): + client=Client(timeout=40) + barrier.wait(timeout=90) + return client.call('POST',path+'race.png',[201,503],actor=alice,raw=original,headers={'Content-Type':'image/png'}) + with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: + pending=[pool.submit(upload,i) for i in range(3)] + barrier.wait(timeout=90) + during=reconcile(True) + created=[json.loads(x['bytes']) for x in (f.result() for f in pending) if x['status']==201] + for item in created: + check(c.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=bob)['bytes']==original,'concurrent upload was deleted') + # Two scan sizes with controlled synthetic orphans. None are eligible during + # measurement; their cleanup is the ordinary grace-based reconciler task. + counts=[] + for batch in (10,100): + keys=['original/'+str(uuid.uuid4()) for _ in range(batch)] + mc("printf 'scan-fixture' >/tmp/scan\n"+'\n'.join("mc cp /tmp/scan local/messenger-attachments/"+k+" >/dev/null" for k in keys)) + timings=[reconcile(False) for _ in range(3)] + counts.append({'added_objects':batch,'runs':timings}) + final=reconcile(False) + save('research.json',{'complete':True,'track':2,'grace_seconds':60, + 'hypothesis':'Per-key locks, durable PostgreSQL rechecks and age threshold remove only old unreferenced objects; missing metadata is retained and recoverable.', + 'faults':['PostgreSQL INSERT exception after successful S3 PUT','S3 object removed after acknowledged upload'], + 'dry_run':dry,'apply':apply,'repeat_apply':repeat,'recovery':recovered,'concurrent':during, + 'fresh_orphan_protected':fresh_key in objects(),'used_original_checksum':hashlib.sha256(original).hexdigest(), + 'scan_cost':counts,'final':final}) + print('PASS Track 2: both failures, dry-run, repair, repeat, fresh/used protection and measured scan cost') + + +if __name__=='__main__': + main() diff --git a/student-tests/unit.py b/student-tests/unit.py new file mode 100644 index 00000000..6248b5c8 --- /dev/null +++ b/student-tests/unit.py @@ -0,0 +1,25 @@ +"""Run private Go tests in a temporary source copy; public files stay untouched.""" +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + +ROOT=Path(__file__).resolve().parents[1] + + +def main(): + subprocess.run([sys.executable, '-X', 'utf8', str(ROOT/'student-tests/readiness_test.py')], cwd=ROOT, check=True) + with tempfile.TemporaryDirectory(prefix='lab4-student-') as folder: + target=Path(folder) + for path in ROOT.glob('*.go'): + shutil.copyfile(path,target/path.name) + for name in ('go.mod','go.sum'): + shutil.copyfile(ROOT/name,target/name) + shutil.copytree(ROOT/'migrations',target/'migrations') + shutil.copyfile(ROOT/'student-tests/validation_test.go',target/'validation_test.go') + subprocess.run(['go','test','-tags','studentvalidation','-count=1','-v','./...'],cwd=target,check=True) + + +if __name__=='__main__': + main() diff --git a/student-tests/validation_test.go b/student-tests/validation_test.go new file mode 100644 index 00000000..d34fb934 --- /dev/null +++ b/student-tests/validation_test.go @@ -0,0 +1,121 @@ +//go:build studentvalidation + +package main + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "errors" + "hash/crc32" + "image" + "image/jpeg" + "image/png" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/minio/minio-go/v7" +) + +func TestAttachmentFilename(t *testing.T) { + for _, name := range []string{"", " ", "../file.png", "a/b", "a\\b", "a\x00b", "a\nb", "a\x7fb", strings.Repeat("я", 256), string([]byte{255})} { + if validFilename(name) { + t.Fatalf("unsafe filename accepted: %q", name) + } + } + for _, name := range []string{"photo.png", "Фотография 😀.jpg", strings.Repeat("я", 255)} { + if !validFilename(name) { + t.Fatalf("valid display name rejected: %q", name) + } + } +} + +func TestAttachmentMessageValidation(t *testing.T) { + id := "12345678-1234-4234-8234-123456789abc" + for _, raw := range []string{`{}`, `{"text":null}`, `{"text":" "}`, `{"text":"ok","attachment_ids":null}`, `{"text":"ok","attachment_ids":[null]}`, `{"text":"ok","attachment_ids":["invalid"]}`, `{"text":"","attachment_ids":["` + id + `","` + strings.ToUpper(id) + `"]}`} { + var body map[string]json.RawMessage + json.Unmarshal([]byte(raw), &body) + if _, _, err := messageFields(body); err == nil { + t.Fatalf("invalid message accepted: %s", raw) + } + } + for _, raw := range []string{`{"text":"ok"}`, `{"text":"ok","attachment_ids":[]}`, `{"text":"","attachment_ids":["` + id + `"]}`} { + var body map[string]json.RawMessage + json.Unmarshal([]byte(raw), &body) + _, ids, err := messageFields(body) + if err != nil || ids == nil { + t.Fatalf("valid message rejected or null IDs: %s", raw) + } + } +} + +func TestUntrustedImagesRejectedBeforeStorage(t *testing.T) { + folder := t.TempDir() + t.Setenv("TMPDIR", folder) + t.Setenv("TMP", folder) + t.Setenv("TEMP", folder) + var encoded bytes.Buffer + png.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 20, 10))) + pngBytes := append([]byte(nil), encoded.Bytes()...) + encoded.Reset() + jpeg.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 20, 10)), nil) + jpegBytes := append([]byte(nil), encoded.Bytes()...) + // Correct IHDR CRC: a valid header proves the pixel guard runs before Decode. + huge := append([]byte(nil), pngBytes...) + binary.BigEndian.PutUint32(huge[16:20], 40000001) + binary.BigEndian.PutUint32(huge[20:24], 1) + binary.BigEndian.PutUint32(huge[29:33], crc32.ChecksumIEEE(huge[12:29])) + for _, tc := range []struct { + name, mime string + data []byte + length int64 + status int + }{ + {"empty", "image/png", nil, 0, 415}, + {"invalid bytes", "image/png", []byte("fake"), 4, 415}, + {"truncated PNG", "image/png", pngBytes[:40], 40, 415}, + {"truncated JPEG", "image/jpeg", jpegBytes[:len(jpegBytes)/2], -1, 415}, + {"spoof PNG", "image/jpeg", pngBytes, -1, 415}, + {"spoof JPEG", "image/png", jpegBytes, -1, 415}, + {"unsupported MIME", "text/plain", pngBytes, -1, 415}, + {"large header", "image/png", pngBytes, maxUploadBytes + 1, 413}, + {"chunked bytes limit", "image/png", bytes.Repeat([]byte("x"), int(maxUploadBytes+1)), -1, 413}, + {"pixel guard", "image/png", huge, -1, 413}, + } { + t.Run(tc.name, func(t *testing.T) { + app := App{uploadSlots: make(chan struct{}, 2), decodeSlot: make(chan struct{}, 1)} + request := httptest.NewRequest("POST", "/attachments?filename=image.png", bytes.NewReader(tc.data)) + request.ContentLength = tc.length + request.Header.Set("Content-Type", tc.mime) + _, err := app.upload(context.Background(), httptest.NewRecorder(), request, "chat", "user") + var failure apiError + if !errors.As(err, &failure) || failure.status != tc.status { + t.Fatalf("expected %d; got %v", tc.status, err) + } + entries, e := os.ReadDir(folder) + if e != nil || len(entries) != 0 { + t.Fatal("temporary upload leaked") + } + }) + } +} + +func TestReconcilerDistinguishesStorageFaults(t *testing.T) { + for _, tc := range []struct { + err error + absent bool + }{ + {nil, false}, {minio.ErrorResponse{Code: "NoSuchKey", StatusCode: 404}, true}, + {minio.ErrorResponse{Code: "AccessDenied", StatusCode: 403}, false}, + {minio.ErrorResponse{Code: "NoSuchBucket", StatusCode: 404}, false}, + {minio.ErrorResponse{Code: "InternalError", StatusCode: 500}, false}, + {context.DeadlineExceeded, false}, + } { + if absentObject(tc.err) != tc.absent { + t.Fatalf("unsafe missing inference: %v", tc.err) + } + } +}