ЛР 2 — БПИ2304 — Кирюпина — на 3 #149
+3
-5
@@ -1,11 +1,9 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
# Created locally by scripts/setup.py; never commit .env or secrets/.
|
||||
APP_HOST=0.0.0.0
|
||||
# Published host port; API always listens on 8080 inside Compose.
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
# Compose mounts the generated secret at this fixed container path.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
*.sh text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
*.sql text eol=lf
|
||||
@@ -0,0 +1,9 @@
|
||||
FROM node:22.20.0-alpine
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev --ignore-scripts
|
||||
COPY src/ ./src/
|
||||
COPY migrations/ ./migrations/
|
||||
ENV APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab
|
||||
EXPOSE 8080
|
||||
CMD ["node", "src/server.js"]
|
||||
@@ -1,37 +1,145 @@
|
||||
# Отчёт — лабораторная 2
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Кирюпина Александра Радиевна, БПИ2304.
|
||||
- Целевая оценка; выбранный трек 5, если нужен: 3, трек 5 не выбран.
|
||||
- Commit/PR: планируемая ветка `solution/bpi2304-kiryupina`, заголовок MR `ЛР 2 — БПИ2304 — Кирюпина — на 3`. Ссылка будет добавлена после создания MR.
|
||||
- Использованные источники, библиотеки и помощь ИИ: контракт и публичные тесты курса, Node.js 22.20.0, pg 8.16.3, PostgreSQL 17.6, Python 3.9+. Реализация продолжает мою lab1. ChatGPT/Codex использовался для подготовки кода, тестов, отчёта и выполнения проверок в локальном Docker. Контракт и публичные тесты не менялись. Документация: [node-postgres](https://node-postgres.com/features/transactions), [параметризованные запросы](https://node-postgres.com/features/queries), [Node.js crypto](https://nodejs.org/docs/latest-v22.x/api/crypto.html).
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Docker Desktop с Linux-контейнерами, доступ к образам и npm registry при первой сборке, Python 3.9+. Проверенный стенд 2026-11-04: Windows, Docker CLI 29.9.2. В проверках использовался Python из окружения Codex. CPU/RAM отдельно не фиксировались, лимиты контейнерам не задавались. Проверена сборка из распакованного проекта и инициализация нового пустого volume; отдельный clone с GitFlic пока не создавался.
|
||||
|
||||
Все команды выполняются из корня проекта, где лежит compose.yaml. Команды ниже для PowerShell. Если Python запускается как python, заменить py на python.
|
||||
|
||||
```powershell
|
||||
py -X utf8 scripts/setup.py
|
||||
py -X utf8 scripts/check_contract.py
|
||||
docker compose config --quiet
|
||||
docker compose up -d --build --wait
|
||||
py -X utf8 tests/smoke.py --base-url http://localhost:8080
|
||||
```
|
||||
|
||||
setup.py создаёт .env из примера и случайный пароль PostgreSQL в secrets/. Уже существующие файлы не заменяются. Пароль не выводится на экран. Секреты подключаются как файлы /run/secrets/postgres_password и /run/secrets/database_url; .env и secrets/ исключены из Git и контекста Docker-сборки.
|
||||
|
||||
Если порт 8080 занят первой лабораторной, её можно остановить отдельно или указать APP_PORT=8082 в локальном .env. Тогда тесты запускать с --base-url http://localhost:8082. База на порт компьютера не публикуется.
|
||||
|
||||
Публичная проверка полного перезапуска на Windows:
|
||||
|
||||
```powershell
|
||||
py -X utf8 tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080
|
||||
```
|
||||
|
||||
restart.cmd запускает restart.ps1. Скрипт фиксирует время старта контейнеров и имя тома, останавливает API и БД, поднимает БД с ожиданием готовности, затем API. Том не удаляется, данные заново не создаются. Прежний токен остаётся только в памяти Python-теста. В evidence/restart-scope.txt записываются состояния контейнеров до и после.
|
||||
|
||||
На Linux используются те же публичные тесты через Makefile:
|
||||
|
||||
```sh
|
||||
python3 scripts/setup.py
|
||||
docker compose up -d --build --wait
|
||||
chmod +x scripts/restart.sh
|
||||
make check
|
||||
make test
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
```
|
||||
|
||||
Фактически в Windows запускались Python-команды, эквивалентные make check, make test и make test-persistence, с Windows-вариантом hook. Linux-hook включён в проект, проверен синтаксически; отдельный Linux-прогон make не выполнялся. При добавлении файлов в Git из Windows нужно сохранить executable bit: git update-index --chmod=+x scripts/restart.sh.
|
||||
|
||||
Собственные API-проверки и проверка SQL-ограничений/повторных миграций:
|
||||
|
||||
```powershell
|
||||
py -X utf8 student-tests/check.py --base-url http://localhost:8080
|
||||
Get-Content student-tests/storage.js -Raw | docker compose exec -T api node
|
||||
```
|
||||
|
||||
Проверка короткого TTL отдельным временным API:
|
||||
|
||||
```powershell
|
||||
.\scripts\check-expiry.ps1
|
||||
```
|
||||
|
||||
Скрипт использует порт 18083, SESSION_TTL_SECONDS=2 и ту же PostgreSQL. После проверки временный контейнер останавливается и удаляется. Конфигурация основного API и срок действия уже созданных сессий не меняются. При блокировке запуска PowerShell-скрипта можно выполнить: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/check-expiry.ps1.
|
||||
|
||||
Повторное применение миграций вручную:
|
||||
|
||||
```powershell
|
||||
docker compose exec api node src/migrate.js
|
||||
```
|
||||
|
||||
Безопасная остановка с сохранением данных:
|
||||
|
||||
```powershell
|
||||
docker compose down
|
||||
```
|
||||
|
||||
Повторный запуск: docker compose up -d --build --wait. Именованный volume сохраняется. Намеренное удаление всех учебных данных выполняется отдельной командой docker compose down -v; для проверки сохранности её применять нельзя. Локальные secrets нужно сохранять вместе с существующим volume: генерация другого пароля не меняет пароль уже созданной БД.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Схема: клиент → HTTP API Node.js → PostgreSQL. Из lab1 перенесены структура маршрутов, проверки JSON и полей, членство в чатах, формат ошибок и идея keyset-пагинации. Map/Set/массивы как хранилище заменены SQL-запросами. X-User-Id заменён Basic/Bearer согласно переходу lab1 → lab2.
|
||||
|
||||
| Роль | Сервис и версия | Проверка готовности | Хранение и доступ |
|
||||
| --- | --- | --- | --- |
|
||||
| API | api, образ mtusi-messenger:lab2 из node:22.20.0-alpine | /health/ready проверяет соединение с БД | localhost:8080, состояние в PostgreSQL |
|
||||
| База | db, postgres:17.6-alpine | pg_isready | volume pgdata, порт 5432 только во внутренней сети |
|
||||
|
||||
Версии npm-зависимостей фиксируются package-lock.json, установка — npm ci. Образы закреплены тегами, digest не закреплён. Контейнер API слушает 0.0.0.0:8080. APP_PORT из .env задаёт опубликованный порт компьютера; внутри Compose порт API остаётся 8080. APP_HOST — адрес внутри контейнера, APP_ENV — подпись окружения, SESSION_TTL_SECONDS — срок новых сессий. SESSION_STORE фиксирован как postgres. DATABASE_URL_FILE указывает на смонтированный файл секрета. Redis/Valkey и CACHE_URL_FILE не используются.
|
||||
|
||||
Схема заранее описана в infra/schema.md. Миграция migrations/001_initial.sql создаёт:
|
||||
|
||||
- users: UUID, уникальный username, display_name, password_hash, created_at;
|
||||
- chats: UUID, title, created_at;
|
||||
- chat_members: составной ключ (chat_id, user_id) и внешние ключи;
|
||||
- messages: UUID, chat_id, sender_id, text, created_at; составной внешний ключ на участника чата;
|
||||
- sessions: хеш токена, user_id и expires_at;
|
||||
- app_settings: постоянный ключ подписи курсоров.
|
||||
|
||||
schema_migrations хранит имя и checksum применённой миграции. При запуске API миграции применяются автоматически под advisory lock. Повторный запуск не вставляет данные заново. Изменение уже применённой миграции обнаруживается по checksum; для новых изменений нужно добавлять новую SQL-миграцию.
|
||||
|
||||
Создание чата и всех его участников выполняется в одной транзакции на одном соединении. Если операция завершается ошибкой, происходит ROLLBACK. Уникальность username обеспечивается базой, в том числе при одновременной регистрации. Значения передаются параметрами, пул ограничен 10 соединениями, заданы таймауты подключения и SQL-запросов. Ответ 201 выдаётся после успешного завершения записи.
|
||||
|
||||
Пароли обрабатываются стандартным scrypt: N=32768, r=8, p=1, случайная соль 16 байт, результат 64 байта. Пароль не хранится открытым и не возвращается в User. При входе POST /api/v1/auth/sessions принимает Basic без тела; пароль может содержать Unicode и двоеточия. Ответ содержит случайный 256-битный токен Bearer. В sessions хранится только SHA-256 этого случайного токена, а не сам токен. Это не замена password KDF: для паролей используется scrypt.
|
||||
|
||||
Каждый защищённый запрос проверяет существование сессии и expires_at по времени БД. Неизвестная, истёкшая или отозванная сессия даёт 401 с WWW-Authenticate. DELETE /api/v1/auth/sessions/current удаляет сессию и возвращает 204. Basic не даёт доступа к бизнес-методам, X-User-Id игнорируется. Регистрация и health остаются публичными. При недоступности БД /health/ready возвращает 503, /health/live не зависит от БД.
|
||||
|
||||
История выбирается SQL-запросом по (created_at, id) с LIMIT, а не загрузкой всей истории в память. Есть индекс (chat_id, created_at, id). Даты хранятся с точностью до миллисекунд, чтобы курсор не терял точность при преобразовании в JavaScript. Курсор подписан и привязан к ресурсу; ключ подписи хранится в PostgreSQL и переживает рестарт. Для неизменной истории нет повторов. Snapshot между запросами не гарантируется: новые записи перед уже пройденным курсором могут не попасть в продолжение, в том числе при изменении часов.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| Критерий README для оценки 3 | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Структура контракта | scripts/check_contract.py | PASS | evidence/check.txt |
|
||||
| Docker-сборка и готовность | docker compose up -d --build --wait | Образ собран, api и db healthy | evidence/build.txt, evidence/containers.txt |
|
||||
| Публичный smoke | tests/smoke.py против контейнера | PASS: lab2 public API scenario | evidence/smoke.txt |
|
||||
| Сохранность данных и действующей сессии | tests/resilience.py --mode persistence --action-script scripts/restart.cmd | Прежний токен читает прежнее сообщение после рестарта API и PostgreSQL | evidence/persistence.txt |
|
||||
| Реальный рестарт всех сервисов без удаления тома | Снимки docker inspect до и после hook | Изменились времена старта API и db, имя pgdata сохранилось | evidence/restart-scope.txt |
|
||||
| PostgreSQL, ограничения и атомарность | student-tests/storage.js | Проверены FK; ошибка вставки участника откатывает созданный чат | evidence/storage.txt |
|
||||
| Повторные миграции | Два вызова migrate в storage.js | Количество записей во всех бизнес-таблицах не изменилось, версия миграции одна | evidence/storage.txt |
|
||||
| Basic/Bearer, logout, Unicode, доступ и страницы | student-tests/check.py | PASS, включая неверный пароль, отзыв и параллельные операции | evidence/student-tests.txt |
|
||||
| Срок действия сессии | scripts/check-expiry.ps1, TTL=2 | После ожидания прежний токен получил 401 | evidence/expiry.txt |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Проверки выполнены при подготовке решения с помощью Codex на локальном Docker-стенде. Они не означают выполнение всех требований на 4: Redis/Valkey и исследование индекса не реализованы.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Целевая оценка — 3. Нагрузочный трек 5 не выполнялся.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Остановка и запуск API и PostgreSQL | Сохранятся сообщение и действующая сессия | Публичный persistence прошёл без повторного входа | Тест дождался ready; отдельно время не измерялось, подтверждённое сообщение не потеряно |
|
||||
| Повторное применение миграций дважды | Данные не дублируются | Счётчики users/chats/chat_members/messages/sessions совпали | Потери данных нет |
|
||||
| Ошибка FK внутри создания чата | Откат всей транзакции | Чат после ROLLBACK отсутствует | Частичного состояния нет |
|
||||
| Logout | Токен отозван | Повторный запрос получил 401 | Данные чатов сохраняются |
|
||||
| TTL=2 секунды | Токен перестаёт действовать | Через 3 секунды получен 401 | Пользователь сохраняется, требуется новый вход |
|
||||
| Четыре регистрации одинакового имени | Один успех, остальные 409 | Один 201, три 409 | Дубликатов пользователей нет |
|
||||
| 20 сообщений из четырёх потоков плюс одно отдельное | 21 уникальное сообщение | История прочитана страницами без потерь и повторов | Все подтверждённые сообщения найдены |
|
||||
|
||||
Это функциональные проверки, а не измерение производительности. RPS, p95/p99, CPU/RAM и время SIGTERM не измерялись.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Обычный перезапуск API и БД с сохранённым volume не теряет данные. Удаление volume, потеря диска или машины не покрываются: резервное копирование и репликация не реализованы. PostgreSQL работает с настройками durability образа по умолчанию; ослабление fsync или synchronous_commit не выполнялось.
|
||||
|
||||
Basic используется по HTTP только на локальном изолированном стенде с синтетическими данными. Для удалённого размещения нужен TLS. Нет Redis, очистки истёкших сессий по расписанию, ограничения числа пользователей/сообщений, вложений и механизмов лабораторной 3. Истёкшие сессии не принимаются, даже если их записи ещё остаются в таблице. Приложение и БД работают с учебными правами, промышленный hardening не заявлен.
|
||||
|
||||
Следующий шаг курса — несколько API-реплик и идемпотентность отправки. Для текущей оценки оставлен один API и одна PostgreSQL.
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
name: mtusi-lab2
|
||||
services:
|
||||
db:
|
||||
image: postgres:17.6-alpine
|
||||
environment:
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_USER: 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: 3s
|
||||
retries: 30
|
||||
api:
|
||||
image: mtusi-messenger:lab2
|
||||
build: .
|
||||
environment:
|
||||
APP_HOST: ${APP_HOST:-0.0.0.0}
|
||||
APP_PORT: 8080
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
SESSION_STORE: postgres
|
||||
secrets:
|
||||
- database_url
|
||||
ports:
|
||||
- "127.0.0.1:${APP_PORT:-8080}:8080"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:8080/health/ready').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
|
||||
interval: 3s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
volumes:
|
||||
pgdata:
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
@@ -0,0 +1,66 @@
|
||||
Image mtusi-messenger:lab2 Building
|
||||
#1 [internal] load local bake definitions
|
||||
#1 reading from stdin 643B 0.0s done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [internal] load build definition from Dockerfile
|
||||
#2 transferring dockerfile: 292B done
|
||||
#2 DONE 0.0s
|
||||
|
||||
#3 [auth] library/node:pull token for registry-1.docker.io
|
||||
#3 DONE 0.0s
|
||||
|
||||
#4 [internal] load metadata for docker.io/library/node:22.20.0-alpine
|
||||
#4 DONE 24.3s
|
||||
|
||||
#5 [internal] load .dockerignore
|
||||
#5 transferring context: 196B done
|
||||
#5 DONE 0.0s
|
||||
|
||||
#6 [internal] load build context
|
||||
#6 transferring context: 12.76kB done
|
||||
#6 DONE 0.0s
|
||||
|
||||
#7 [1/6] FROM docker.io/library/node:22.20.0-alpine@sha256:dbcedd8aeab47fbc0f4dd4bffa55b7c3c729a707875968d467aaaea42d6225af
|
||||
#7 resolve docker.io/library/node:22.20.0-alpine@sha256:dbcedd8aeab47fbc0f4dd4bffa55b7c3c729a707875968d467aaaea42d6225af 0.0s done
|
||||
#7 DONE 0.0s
|
||||
|
||||
#8 [2/6] WORKDIR /app
|
||||
#8 CACHED
|
||||
|
||||
#9 [3/6] COPY package.json package-lock.json ./
|
||||
#9 CACHED
|
||||
|
||||
#10 [4/6] RUN npm ci --omit=dev --ignore-scripts
|
||||
#10 CACHED
|
||||
|
||||
#11 [5/6] COPY src/ ./src/
|
||||
#11 DONE 0.0s
|
||||
|
||||
#12 [6/6] COPY migrations/ ./migrations/
|
||||
#12 DONE 0.0s
|
||||
|
||||
#13 exporting to image
|
||||
#13 exporting layers 0.1s done
|
||||
#13 exporting manifest sha256:6caefe8042b93970bec436ac0374ddc04184971877b30d1185f4b6d98688dd64 0.0s done
|
||||
#13 exporting config sha256:ad998a9332da92ba6e41df8e97e2302424186ba888597ecd45d6d44403081ced 0.0s done
|
||||
#13 exporting attestation manifest sha256:9c5a62e74488cf5521136bec981299a5cf89dd75ee6fd0b0430a80d94056bd93 0.0s done
|
||||
#13 exporting manifest list sha256:dd0b9ec059228dc6b150a01e8e4b2717cfadc50ec1625d78858d0a70ec761e20 0.0s done
|
||||
#13 naming to docker.io/library/mtusi-messenger:lab2 done
|
||||
#13 unpacking to docker.io/library/mtusi-messenger:lab2 0.0s done
|
||||
#13 DONE 0.3s
|
||||
|
||||
#14 resolving provenance for metadata file
|
||||
#14 DONE 0.0s
|
||||
Image mtusi-messenger:lab2 Built
|
||||
Container mtusi-lab2-db-1 Running
|
||||
Container mtusi-lab2-api-1 Recreate
|
||||
Container mtusi-lab2-api-1 Recreated
|
||||
Container mtusi-lab2-db-1 Waiting
|
||||
Container mtusi-lab2-db-1 Healthy
|
||||
Container mtusi-lab2-api-1 Starting
|
||||
Container mtusi-lab2-api-1 Started
|
||||
Container mtusi-lab2-api-1 Waiting
|
||||
Container mtusi-lab2-db-1 Waiting
|
||||
Container mtusi-lab2-db-1 Healthy
|
||||
Container mtusi-lab2-api-1 Healthy
|
||||
@@ -0,0 +1 @@
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
@@ -0,0 +1,3 @@
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi-lab2-api-1 mtusi-messenger:lab2 "docker-entrypoint.s…" api 3 minutes ago Up 3 minutes (healthy) 127.0.0.1:8080->8080/tcp
|
||||
mtusi-lab2-db-1 postgres:17.6-alpine "docker-entrypoint.s…" db 13 minutes ago Up 7 minutes (healthy) 5432/tcp
|
||||
@@ -0,0 +1,3 @@
|
||||
Container mtusi-lab2-api-run-9ddc97b70e93 Creating
|
||||
Container mtusi-lab2-api-run-9ddc97b70e93 Created
|
||||
PASS: SESSION_TTL_SECONDS=2 expires existing token; no token printed.
|
||||
@@ -0,0 +1,2 @@
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
@@ -0,0 +1,4 @@
|
||||
/mtusi-lab2-api-1 started=2026-11-04T11:27:49.324815141Z status=running volumes=
|
||||
/mtusi-lab2-db-1 started=2026-11-04T11:27:45.76343575Z status=running volumes= mtusi-lab2_pgdata
|
||||
/mtusi-lab2-api-1 started=2026-11-04T11:29:08.127461817Z status=running volumes=
|
||||
/mtusi-lab2-db-1 started=2026-11-04T11:29:04.556726577Z status=running volumes= mtusi-lab2_pgdata
|
||||
@@ -0,0 +1 @@
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,2 @@
|
||||
PASS: two repeated migrations preserve all row counts; FK failure rolls back chat insert; foreign keys present.
|
||||
{"counts":{"users":"14","chats":"5","chat_members":"9","messages":"25","sessions":"11"},"constraints":[{"contype":"c","n":4},{"contype":"f","n":4},{"contype":"p","n":7},{"contype":"u","n":1}]}
|
||||
@@ -0,0 +1 @@
|
||||
PASS: Basic/Bearer/logout, Unicode passwords with colon, validation, membership, atomic invalid chat, username race and pagination of 21 messages.
|
||||
@@ -0,0 +1,23 @@
|
||||
# Схема и границы операций
|
||||
|
||||
До переноса обработчиков на SQL выбрана следующая схема:
|
||||
|
||||
- users: UUID PK, username UNIQUE, display_name, password_hash, created_at.
|
||||
- chats: UUID PK, title, created_at.
|
||||
- chat_members: составной PK (chat_id, user_id), FK на chats и users.
|
||||
- messages: UUID PK, chat_id, sender_id, text, created_at; составной FK
|
||||
(chat_id, sender_id) на chat_members запрещает запись от постороннего.
|
||||
- sessions: SHA-256 случайного токена как PK, FK user_id, expires_at.
|
||||
- app_settings: постоянный ключ подписи курсоров. Не меняется при рестарте.
|
||||
- schema_migrations: номер применённой SQL-миграции и её checksum.
|
||||
|
||||
Индексы: уникальный username; история (chat_id, created_at, id);
|
||||
список чатов (created_at, id); членство (user_id, chat_id); expiry сессий.
|
||||
Время timestamptz(3), чтобы точность курсора JavaScript совпадала с PostgreSQL.
|
||||
|
||||
Создание чата и вставка всех участников — одна транзакция на одном соединении:
|
||||
проверка участников, INSERT chats, INSERT chat_members, COMMIT. При ошибке ROLLBACK.
|
||||
Остальные изменения — одиночные атомарные SQL-операции. Чтение сообщения идёт
|
||||
из PostgreSQL, без кэша. Пользователю отвечаем 201 только после успешной записи.
|
||||
Миграции выполняются под advisory lock, каждая вместе с записью версии — в транзакции.
|
||||
Повторный запуск проверяет checksum и пропускает уже применённые версии.
|
||||
@@ -0,0 +1,35 @@
|
||||
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(3) 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(3) 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 TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
created_at timestamptz(3) NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||
);
|
||||
CREATE TABLE sessions (
|
||||
token_hash text PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
expires_at timestamptz(3) NOT NULL
|
||||
);
|
||||
CREATE TABLE app_settings (key text PRIMARY KEY, value text NOT NULL);
|
||||
CREATE INDEX messages_history ON messages(chat_id, created_at, id);
|
||||
CREATE INDEX chats_order ON chats(created_at, id);
|
||||
CREATE INDEX member_chats ON chat_members(user_id, chat_id);
|
||||
CREATE INDEX sessions_expiry ON sessions(expires_at);
|
||||
Generated
+161
@@ -0,0 +1,161 @@
|
||||
{
|
||||
"name": "mtusi-lab2-messenger",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "mtusi-lab2-messenger",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"pg": "8.16.3"
|
||||
}
|
||||
},
|
||||
"node_modules/pg": {
|
||||
"version": "8.16.3",
|
||||
"resolved": "https://registry.npmjs.org/pg/-/pg-8.16.3.tgz",
|
||||
"integrity": "sha512-enxc1h0jA/aq5oSDMvqyW3q89ra6XIIDZgCX9vkMrnz5DFTw/Ny3Li2lFQ+pt3L6MCgm/5o2o8HW9hiJji+xvw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-connection-string": "^2.9.1",
|
||||
"pg-pool": "^3.10.1",
|
||||
"pg-protocol": "^1.10.3",
|
||||
"pg-types": "2.2.0",
|
||||
"pgpass": "1.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"pg-cloudflare": "^1.2.7"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"pg-native": ">=3.0.1"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"pg-native": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/pg-cloudflare": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
|
||||
"integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/pg-connection-string": {
|
||||
"version": "2.14.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
|
||||
"integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-int8": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
|
||||
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pg-pool": {
|
||||
"version": "3.14.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
|
||||
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"pg": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pg-protocol": {
|
||||
"version": "1.16.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
|
||||
"integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-types": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
|
||||
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-int8": "1.0.1",
|
||||
"postgres-array": "~2.0.0",
|
||||
"postgres-bytea": "~1.0.0",
|
||||
"postgres-date": "~1.0.4",
|
||||
"postgres-interval": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/pgpass": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
|
||||
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"split2": "^4.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-array": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-bytea": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
|
||||
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-date": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
|
||||
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-interval": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
|
||||
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"xtend": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/split2": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
|
||||
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">= 10.x"
|
||||
}
|
||||
},
|
||||
"node_modules/xtend": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.4"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "mtusi-lab2-messenger",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": { "start": "node src/server.js", "migrate": "node src/migrate.js" },
|
||||
"dependencies": { "pg": "8.16.3" }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
param([string]$PythonCommand = 'py')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Push-Location (Split-Path $PSScriptRoot -Parent)
|
||||
$containerId = $null
|
||||
try {
|
||||
# An extra temporary API shares PostgreSQL but issues only two-second sessions.
|
||||
# The main API and its existing sessions are not reconfigured.
|
||||
$containerId = docker compose run -d --rm --no-deps -p 127.0.0.1:18083:8080 -e SESSION_TTL_SECONDS=2 api
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Temporary API failed to start' }
|
||||
$ready = $false
|
||||
for ($i=0; $i -lt 30; $i++) {
|
||||
try {
|
||||
$null = Invoke-RestMethod http://127.0.0.1:18083/health/ready -TimeoutSec 2
|
||||
$ready = $true
|
||||
break
|
||||
} catch { Start-Sleep -Milliseconds 500 }
|
||||
}
|
||||
if (-not $ready) { throw 'Temporary API not ready' }
|
||||
& $PythonCommand -X utf8 student-tests/check.py --base-url http://127.0.0.1:18083 --expiry
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Expiry test failed' }
|
||||
} finally {
|
||||
if ($containerId) { docker stop $containerId | Out-Null }
|
||||
Pop-Location
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.ps1"
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,20 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Push-Location (Split-Path $PSScriptRoot -Parent)
|
||||
try {
|
||||
function Snapshot {
|
||||
foreach ($service in @('api', 'db')) {
|
||||
$containerId = docker compose ps -q $service
|
||||
if ($LASTEXITCODE -ne 0 -or -not $containerId) { throw 'Container not found' }
|
||||
docker inspect --format '{{.Name}} started={{.State.StartedAt}} status={{.State.Status}} volumes={{range .Mounts}}{{.Name}} {{end}}' $containerId
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Inspect failed' }
|
||||
}
|
||||
}
|
||||
Snapshot | Set-Content evidence/restart-scope.txt
|
||||
docker compose stop api db
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Stop failed' }
|
||||
docker compose up -d --wait --wait-timeout 30 db
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Database start failed' }
|
||||
docker compose up -d --wait --wait-timeout 30 api
|
||||
if ($LASTEXITCODE -ne 0) { throw 'API start failed' }
|
||||
Snapshot | Add-Content evidence/restart-scope.txt
|
||||
} finally { Pop-Location }
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
snapshot() {
|
||||
for service in api db; do
|
||||
id=$(docker compose ps -q "$service")
|
||||
docker inspect --format '{{.Name}} started={{.State.StartedAt}} status={{.State.Status}} mounts={{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}' "$id"
|
||||
done
|
||||
}
|
||||
snapshot > evidence/restart-scope.txt
|
||||
docker compose stop api db
|
||||
docker compose up -d --wait --wait-timeout 30 db
|
||||
docker compose up -d --wait --wait-timeout 30 api
|
||||
snapshot >> evidence/restart-scope.txt
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Generate local credentials once; never print or rotate existing secrets."""
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
directory = root / 'secrets'
|
||||
directory.mkdir(exist_ok=True)
|
||||
password_file = directory / 'postgres_password'
|
||||
url_file = directory / 'database_url'
|
||||
if password_file.exists() != url_file.exists():
|
||||
raise SystemExit('Incomplete secrets: restore the missing file; do not rotate an existing database password.')
|
||||
if not password_file.exists():
|
||||
password = secrets.token_hex(32)
|
||||
password_file.write_text(password + '\n', encoding='utf-8')
|
||||
url_file.write_text('postgresql://messenger:' + password + '@db:5432/messenger\n', encoding='utf-8')
|
||||
password_file.chmod(0o600)
|
||||
url_file.chmod(0o600)
|
||||
if not (root / '.env').exists():
|
||||
shutil.copyfile(root / '.env.example', root / '.env')
|
||||
print('Local .env and secrets ready; values are not printed. Existing credentials preserved.')
|
||||
@@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
const { readFileSync } = require('node:fs');
|
||||
const { Pool } = require('pg');
|
||||
const pool = new Pool({
|
||||
connectionString: readFileSync(process.env.DATABASE_URL_FILE || '/run/secrets/database_url', 'utf8').trim(),
|
||||
max: 10, connectionTimeoutMillis: 3000, idleTimeoutMillis: 10000,
|
||||
statement_timeout: 5000,
|
||||
});
|
||||
pool.on('error', () => console.error('Database connection unavailable'));
|
||||
async function transaction(work) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const result = await work(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw error;
|
||||
} finally { client.release(); }
|
||||
}
|
||||
module.exports = { pool, transaction };
|
||||
@@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
const { readFileSync, readdirSync } = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createHash, randomBytes } = require('node:crypto');
|
||||
const { pool } = require('./db');
|
||||
async function migrate() {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('SELECT pg_advisory_lock(202602)');
|
||||
await client.query(`CREATE TABLE IF NOT EXISTS schema_migrations
|
||||
(version text PRIMARY KEY, checksum text NOT NULL)`);
|
||||
const dir = path.join(__dirname, '..', 'migrations');
|
||||
for (const version of readdirSync(dir).filter(f => /^\d+.*\.sql$/.test(f)).sort()) {
|
||||
const sql = readFileSync(path.join(dir, version), 'utf8');
|
||||
const checksum = createHash('sha256').update(sql).digest('hex');
|
||||
const existing = await client.query('SELECT checksum FROM schema_migrations WHERE version=$1', [version]);
|
||||
if (existing.rowCount) {
|
||||
if (existing.rows[0].checksum !== checksum) throw new Error('Migration checksum mismatch');
|
||||
continue;
|
||||
}
|
||||
await client.query('BEGIN');
|
||||
try {
|
||||
await client.query(sql);
|
||||
await client.query('INSERT INTO schema_migrations VALUES ($1,$2)', [version, checksum]);
|
||||
await client.query('COMMIT');
|
||||
} catch (error) { await client.query('ROLLBACK'); throw error; }
|
||||
console.log('Applied migration ' + version);
|
||||
}
|
||||
await client.query(`INSERT INTO app_settings VALUES ('cursor_secret',$1) ON CONFLICT DO NOTHING`, [randomBytes(32).toString('hex')]);
|
||||
} finally {
|
||||
await client.query('SELECT pg_advisory_unlock(202602)').catch(() => {});
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
module.exports = { migrate };
|
||||
if (require.main === module) migrate().then(() => console.log('Migrations up to date'))
|
||||
.catch(() => { console.error('Migration failed'); process.exitCode = 1; }).finally(() => pool.end());
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
'use strict';
|
||||
const http = require('node:http');
|
||||
const { randomUUID, randomBytes, createHash, createHmac, scrypt, timingSafeEqual } = require('node:crypto');
|
||||
const { promisify } = require('node:util');
|
||||
const { pool, transaction } = require('./db');
|
||||
const { migrate } = require('./migrate');
|
||||
const derive = promisify(scrypt);
|
||||
const kdfOptions = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
|
||||
const ttl = Number(process.env.SESSION_TTL_SECONDS || 3600);
|
||||
if (!Number.isSafeInteger(ttl) || ttl < 1) throw new Error('Invalid SESSION_TTL_SECONDS');
|
||||
let cursorSecret;
|
||||
const userColumns = 'id, username, display_name, created_at';
|
||||
const chatSelect = `SELECT c.id,c.title,c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id) AS member_ids FROM chats c`;
|
||||
function fail(status, code, message) { throw Object.assign(new Error(message), { status, code }); }
|
||||
function invalid(message = 'Invalid request') { fail(400, 'invalid_request', message); }
|
||||
function unauthorized() { fail(401, 'unauthorized', 'Invalid credentials or session'); }
|
||||
function uuid(value) {
|
||||
if (typeof value !== 'string' || value.length !== 36 || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)) invalid('Invalid UUID');
|
||||
return value.toLowerCase();
|
||||
}
|
||||
function fields(body, names) {
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body) ||
|
||||
Object.keys(body).length !== names.length || !names.every(k => Object.hasOwn(body, k))) invalid('Invalid fields');
|
||||
}
|
||||
function string(value, max, min = 1) {
|
||||
if (typeof value !== 'string' || !value.isWellFormed() || /^[\p{White_Space}\uFEFF]*$/u.test(value) ||
|
||||
[...value].length < min || [...value].length > max || value.includes('\0')) invalid('Invalid string');
|
||||
return value;
|
||||
}
|
||||
function username(value) {
|
||||
if (typeof value !== 'string' || value.length < 3 || value.length > 32 || /[^a-z0-9_]/.test(value)) invalid('Invalid username');
|
||||
}
|
||||
function password(value) {
|
||||
if (typeof value !== 'string' || !value.isWellFormed() || [...value].length < 12 || [...value].length > 128 ||
|
||||
/^[\p{White_Space}\uFEFF]*$/u.test(value)) invalid('Invalid password');
|
||||
}
|
||||
function digest(token) { return createHash('sha256').update(token).digest('hex'); }
|
||||
async function hashPassword(value) {
|
||||
const salt = randomBytes(16).toString('hex');
|
||||
const hash = await derive(value, salt, 64, kdfOptions);
|
||||
return `scrypt$32768$8$1$${salt}$${hash.toString('hex')}`;
|
||||
}
|
||||
const dummySalt = randomBytes(16).toString('hex');
|
||||
async function verifyPassword(value, encoded) {
|
||||
const parts = encoded?.split('$');
|
||||
const salt = parts ? parts[4] : dummySalt;
|
||||
const expected = parts ? Buffer.from(parts[5], 'hex') : Buffer.alloc(64);
|
||||
const actual = await derive(value, salt, 64, kdfOptions);
|
||||
return Boolean(encoded) && expected.length === actual.length && timingSafeEqual(expected, actual);
|
||||
}
|
||||
async function rawBody(req) {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of req) {
|
||||
size += chunk.length;
|
||||
if (size > 1024 * 1024) fail(413, 'payload_too_large', 'Request body too large');
|
||||
chunks.push(chunk);
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
async function body(req) {
|
||||
if (req.headers['content-type']?.split(';')[0].trim().toLowerCase() !== 'application/json')
|
||||
fail(415, 'unsupported_media_type', 'Expected application/json');
|
||||
const bytes = await rawBody(req);
|
||||
try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
|
||||
catch { invalid('Invalid JSON'); }
|
||||
}
|
||||
async function identity(req) {
|
||||
const match = /^Bearer ([A-Za-z0-9_-]{43})$/i.exec(req.headers.authorization || '');
|
||||
if (!match) unauthorized();
|
||||
const tokenHash = digest(match[1]);
|
||||
const result = await pool.query(`SELECT u.id,u.username,u.display_name,u.created_at
|
||||
FROM sessions s JOIN users u ON u.id=s.user_id
|
||||
WHERE token_hash=$1 AND expires_at > clock_timestamp()`, [tokenHash]);
|
||||
if (!result.rowCount) unauthorized();
|
||||
return { user: result.rows[0], tokenHash };
|
||||
}
|
||||
async function accessible(id, user) {
|
||||
const result = await pool.query(chatSelect + ` WHERE c.id=$1 AND EXISTS
|
||||
(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2)`, [uuid(id), user.id]);
|
||||
if (!result.rowCount) fail(404, 'not_found', 'Object not found');
|
||||
return result.rows[0];
|
||||
}
|
||||
function signature(payload) { return createHmac('sha256', cursorSecret).update(payload).digest('base64url'); }
|
||||
function pagination(query, scope) {
|
||||
if (query.getAll('limit').length > 1 || query.getAll('cursor').length > 1) invalid();
|
||||
const raw = query.get('limit') ?? '50';
|
||||
if (!/^\d+$/.test(raw) || Number(raw) < 1 || Number(raw) > 100) invalid('Invalid limit');
|
||||
let after = null;
|
||||
if (query.has('cursor')) {
|
||||
try {
|
||||
const token = query.get('cursor');
|
||||
if (!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token)) throw new Error();
|
||||
const [payload, mac] = token.split('.');
|
||||
if (signature(payload) !== mac) throw new Error();
|
||||
after = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
||||
if (after.scope !== scope || typeof after.created_at !== 'string' || !Number.isFinite(Date.parse(after.created_at))) throw new Error();
|
||||
uuid(after.id);
|
||||
} catch { invalid('Invalid cursor'); }
|
||||
}
|
||||
return { limit: Number(raw), after, scope };
|
||||
}
|
||||
function page(rows, paging) {
|
||||
const items = rows.slice(0, paging.limit);
|
||||
let next_cursor = null;
|
||||
if (rows.length > paging.limit) {
|
||||
const last = items.at(-1);
|
||||
const payload = Buffer.from(JSON.stringify({ scope: paging.scope, created_at: last.created_at, id: last.id })).toString('base64url');
|
||||
next_cursor = payload + '.' + signature(payload);
|
||||
}
|
||||
return { items, next_cursor };
|
||||
}
|
||||
async function route(req) {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
const path = url.pathname, method = req.method;
|
||||
if (method === 'GET' && path === '/health/live') return [200, { status: 'ok' }];
|
||||
if (method === 'GET' && path === '/health/ready') {
|
||||
try { await pool.query('SELECT 1'); }
|
||||
catch { fail(503, 'unavailable', 'Database unavailable'); }
|
||||
return [200, { status: 'ok' }];
|
||||
}
|
||||
if (method === 'POST' && path === '/api/v1/users') {
|
||||
const data = await body(req);
|
||||
fields(data, ['username', 'display_name', 'password']);
|
||||
username(data.username); string(data.display_name, 100); password(data.password);
|
||||
const hash = await hashPassword(data.password);
|
||||
try {
|
||||
const result = await pool.query(`INSERT INTO users(id,username,display_name,password_hash)
|
||||
VALUES($1,$2,$3,$4) RETURNING ${userColumns}`, [randomUUID(), data.username, data.display_name, hash]);
|
||||
return [201, result.rows[0]];
|
||||
} catch (error) {
|
||||
if (error.code === '23505') fail(409, 'conflict', 'Username already exists');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (method === 'POST' && path === '/api/v1/auth/sessions') {
|
||||
const match = /^Basic ([A-Za-z0-9+/]+={0,2})$/i.exec(req.headers.authorization || '');
|
||||
if (!match) unauthorized();
|
||||
let name, value;
|
||||
try {
|
||||
const bytes = Buffer.from(match[1], 'base64');
|
||||
if (bytes.toString('base64') !== match[1]) throw new Error();
|
||||
const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
||||
const colon = decoded.indexOf(':');
|
||||
if (colon < 0) throw new Error();
|
||||
name = decoded.slice(0, colon); value = decoded.slice(colon + 1);
|
||||
username(name); password(value);
|
||||
} catch { unauthorized(); }
|
||||
if ((await rawBody(req)).length) invalid('Login must not have a body');
|
||||
const result = await pool.query(`SELECT ${userColumns},password_hash FROM users WHERE username=$1`, [name]);
|
||||
const row = result.rows[0];
|
||||
if (!await verifyPassword(value, row?.password_hash)) unauthorized();
|
||||
const { password_hash, ...user } = row;
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const session = await pool.query(`INSERT INTO sessions(token_hash,user_id,expires_at)
|
||||
VALUES($1,$2,clock_timestamp()+$3*interval '1 second') RETURNING expires_at`, [digest(token), user.id, ttl]);
|
||||
return [201, { token, token_type: 'Bearer', expires_at: session.rows[0].expires_at, user }];
|
||||
}
|
||||
const { user, tokenHash } = await identity(req);
|
||||
if (method === 'DELETE' && path === '/api/v1/auth/sessions/current') {
|
||||
await pool.query('DELETE FROM sessions WHERE token_hash=$1', [tokenHash]);
|
||||
return [204, null];
|
||||
}
|
||||
if (method === 'GET' && path === '/api/v1/users/me') return [200, user];
|
||||
if (path === '/api/v1/chats' && method === 'POST') {
|
||||
const data = await body(req);
|
||||
fields(data, ['title', 'member_ids']); string(data.title, 100);
|
||||
if (!Array.isArray(data.member_ids) || data.member_ids.length < 1 || data.member_ids.length > 100) invalid('Invalid members');
|
||||
const ids = data.member_ids.map(uuid);
|
||||
if (new Set(ids).size !== ids.length || !ids.includes(user.id)) invalid('Invalid members');
|
||||
return [201, await transaction(async client => {
|
||||
const known = await client.query('SELECT id FROM users WHERE id=ANY($1::uuid[])', [ids]);
|
||||
if (known.rowCount !== ids.length) invalid('Unknown member');
|
||||
const chat = (await client.query('INSERT INTO chats(id,title) VALUES($1,$2) RETURNING *', [randomUUID(), data.title])).rows[0];
|
||||
await client.query('INSERT INTO chat_members(chat_id,user_id) SELECT $1,unnest($2::uuid[])', [chat.id, ids]);
|
||||
return { ...chat, member_ids: ids.sort() };
|
||||
})];
|
||||
}
|
||||
if (path === '/api/v1/chats' && method === 'GET') {
|
||||
const paging = pagination(url.searchParams, 'chats:' + user.id);
|
||||
const rows = (await pool.query(chatSelect + ` WHERE EXISTS
|
||||
(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$1)
|
||||
AND ($2::timestamptz IS NULL OR (c.created_at,c.id)>($2::timestamptz,$3::uuid))
|
||||
ORDER BY c.created_at,c.id LIMIT $4`, [user.id, paging.after?.created_at ?? null, paging.after?.id ?? null, paging.limit + 1])).rows;
|
||||
return [200, page(rows, paging)];
|
||||
}
|
||||
const match = path.match(/^\/api\/v1\/chats\/([^/]+)(\/messages)?$/);
|
||||
if (match) {
|
||||
const chat = await accessible(match[1], user);
|
||||
if (!match[2] && method === 'GET') return [200, chat];
|
||||
if (match[2] && method === 'POST') {
|
||||
const data = await body(req); fields(data, ['text']); string(data.text, 4000);
|
||||
const result = await pool.query(`INSERT INTO messages(id,chat_id,sender_id,text)
|
||||
VALUES($1,$2,$3,$4) RETURNING *`, [randomUUID(), chat.id, user.id, data.text]);
|
||||
return [201, result.rows[0]];
|
||||
}
|
||||
if (match[2] && method === 'GET') {
|
||||
const paging = pagination(url.searchParams, 'messages:' + chat.id);
|
||||
const result = await pool.query(`SELECT * FROM messages WHERE chat_id=$1
|
||||
AND ($2::timestamptz IS NULL OR (created_at,id)>($2::timestamptz,$3::uuid))
|
||||
ORDER BY created_at,id LIMIT $4`, [chat.id, paging.after?.created_at ?? null, paging.after?.id ?? null, paging.limit + 1]);
|
||||
return [200, page(result.rows, paging)];
|
||||
}
|
||||
}
|
||||
fail(404, 'not_found', 'Object not found');
|
||||
}
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const request_id = randomUUID();
|
||||
let status, data;
|
||||
const headers = { 'Content-Type': 'application/json; charset=utf-8', 'X-Request-Id': request_id };
|
||||
try { [status, data] = await route(req); }
|
||||
catch (error) {
|
||||
status = error.status || (/^(08|53|57)/.test(error.code || '') || ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT'].includes(error.code) ? 503 : 500);
|
||||
data = { error: { code: error.status ? error.code : status === 503 ? 'unavailable' : 'internal_error',
|
||||
message: error.status ? error.message : status === 503 ? 'Database unavailable' : 'Internal error', request_id } };
|
||||
if (status === 401) headers['WWW-Authenticate'] = req.url.split('?')[0] === '/api/v1/auth/sessions'
|
||||
? 'Basic realm="messenger", charset="UTF-8"' : 'Bearer realm="messenger"';
|
||||
}
|
||||
res.writeHead(status, headers);
|
||||
res.end(status === 204 ? undefined : JSON.stringify(data));
|
||||
});
|
||||
async function main() {
|
||||
await migrate();
|
||||
cursorSecret = (await pool.query("SELECT value FROM app_settings WHERE key='cursor_secret'")).rows[0].value;
|
||||
server.listen(Number(process.env.APP_PORT || 8080), process.env.APP_HOST || '0.0.0.0', () => console.log('Messenger lab2 ready; environment=' + (process.env.APP_ENV || 'lab')));
|
||||
}
|
||||
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => {
|
||||
server.close(() => pool.end());
|
||||
setTimeout(() => process.exit(1), 9000).unref();
|
||||
});
|
||||
main().catch(() => { console.error('Startup failed: check database and migrations'); process.exitCode = 1; pool.end(); });
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Additional black-box tests. Server must already be running; no secrets printed."""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import threading
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab2 student checks', lambda p: p.add_argument('--expiry', action='store_true'))
|
||||
c = Client(args.base_url)
|
||||
if args.expiry:
|
||||
actor = c.user('expiry')
|
||||
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||
time.sleep(3)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
print('PASS: SESSION_TTL_SECONDS=2 expires existing token; no token printed.')
|
||||
return
|
||||
a, b, outsider, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
for raw in (b'{', b'null', b'[]', b'\xff'):
|
||||
c.call('POST', path, 400, actor=a, raw=raw, headers={'Content-Type': 'application/json'})
|
||||
for data in ({'text': '\u0085'}, {'text': ' \t\n'}, {'text': 42}, {'text': 'x', 'sender_id': a['id']}):
|
||||
c.call('POST', path, 400, actor=a, body=data)
|
||||
for field in ('display_name', 'password'):
|
||||
bad = {**a['registration'], 'username': 'z_' + uuid.uuid4().hex[:12], field: '\u0085'}
|
||||
c.call('POST', '/api/v1/users', 400, body=bad)
|
||||
c.call('GET', path, 404, actor=outsider)
|
||||
c.call('POST', path, 404, actor=outsider, body={'text': 'hidden'})
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': a['id']})
|
||||
c.call('GET', '/api/v1/users/me', actor=a, headers={'X-User-Id': outsider['id']}, schema='User')
|
||||
registration = {'username': 'unicode_' + uuid.uuid4().hex[:10], 'display_name': 'Александра 😀', 'password': 'пароль:😀' * 10}
|
||||
c.call('POST', '/api/v1/users', 201, body=registration, schema='User')
|
||||
credential = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
|
||||
login = c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
||||
actor = {'id': login['user']['id'], 'token': login['token']}
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Basic ' + credential})
|
||||
c.call('POST', '/api/v1/auth/sessions', 400, headers={'Authorization': 'Basic ' + credential}, body={})
|
||||
wrong = base64.b64encode((registration['username'] + ':wrong-password-123').encode()).decode()
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + wrong})
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=actor)
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=actor)
|
||||
before = c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json']
|
||||
c.call('POST', '/api/v1/chats', 400, actor=a, body={'title': 'Invalid', 'member_ids': [a['id'], str(uuid.uuid4())]})
|
||||
after = c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json']
|
||||
check(before == after, 'Invalid chat left partial state')
|
||||
registration = {**a['registration'], 'username': 'race_' + uuid.uuid4().hex[:12]}
|
||||
workers = threading.local()
|
||||
def initialize():
|
||||
workers.client = Client(args.base_url)
|
||||
def register(_):
|
||||
return workers.client.call('POST', '/api/v1/users', [201, 409], body=registration)['status']
|
||||
with ThreadPoolExecutor(max_workers=4, initializer=initialize) as pool:
|
||||
results = list(pool.map(register, range(4)))
|
||||
check(results.count(201) == 1 and results.count(409) == 3, 'Username uniqueness race')
|
||||
sent = list(pool.map(lambda i: workers.client.message(a, chat, 'Проверка ' + str(i))['json'], range(20)))
|
||||
c.message(b, chat, '😀' * 4000)
|
||||
seen, cursor, first_cursor = [], None, None
|
||||
while True:
|
||||
query = '?limit=3' + ('&cursor=' + quote(cursor, safe='') if cursor else '')
|
||||
response = c.call('GET', path + query, actor=b, schema='MessagePage')['json']
|
||||
seen.extend(response['items'])
|
||||
cursor = response['next_cursor']
|
||||
first_cursor = first_cursor or cursor
|
||||
if cursor is None:
|
||||
break
|
||||
check(len(seen) == 21 and len({m['id'] for m in seen}) == 21, 'Pagination lost/duplicated records')
|
||||
check(all(m in seen for m in sent), 'Confirmed message missing')
|
||||
for query in ('?limit=0', '?limit=101', '?cursor=', '?cursor=bad'):
|
||||
c.call('GET', path + query, 400, actor=a)
|
||||
second = c.call('POST', '/api/v1/chats', 201, actor=a, body={'title': 'Second', 'member_ids': [a['id']]}, schema='Chat')['json']
|
||||
c.call('GET', '/api/v1/chats/' + second['id'] + '/messages?cursor=' + quote(first_cursor), 400, actor=a)
|
||||
p1 = c.call('GET', '/api/v1/chats?limit=1', actor=a, schema='ChatPage')['json']
|
||||
p2 = c.call('GET', '/api/v1/chats?limit=100&cursor=' + quote(p1['next_cursor']), actor=a, schema='ChatPage')['json']
|
||||
check(len(p1['items'] + p2['items']) == 2 and p2['next_cursor'] is None, 'Chat pagination')
|
||||
print('PASS: Basic/Bearer/logout, Unicode passwords with colon, validation, membership, atomic invalid chat, username race and pagination of 21 messages.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
// Run inside the API container with: node < student-tests/storage.js
|
||||
const assert = require('node:assert/strict');
|
||||
const { pool, transaction } = require('./src/db');
|
||||
const { migrate } = require('./src/migrate');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
async function counts() {
|
||||
const result = {};
|
||||
for (const table of ['users', 'chats', 'chat_members', 'messages', 'sessions'])
|
||||
result[table] = (await pool.query(`SELECT count(*) AS n FROM ${table}`)).rows[0].n;
|
||||
return result;
|
||||
}
|
||||
async function main() {
|
||||
const before = await counts();
|
||||
await migrate(); await migrate();
|
||||
assert.deepEqual(await counts(), before);
|
||||
assert.equal((await pool.query('SELECT count(*)::int AS n FROM schema_migrations')).rows[0].n, 1);
|
||||
const id = randomUUID();
|
||||
await assert.rejects(transaction(async client => {
|
||||
await client.query('INSERT INTO chats(id,title) VALUES($1,$2)', [id, 'Rollback test']);
|
||||
await client.query('INSERT INTO chat_members VALUES($1,$2)', [id, randomUUID()]);
|
||||
}), e => e.code === '23503');
|
||||
assert.equal((await pool.query('SELECT id FROM chats WHERE id=$1', [id])).rowCount, 0);
|
||||
const constraints = (await pool.query(`SELECT contype,count(*)::int AS n FROM pg_constraint
|
||||
WHERE connamespace='public'::regnamespace GROUP BY contype`)).rows;
|
||||
assert.ok(constraints.some(c => c.contype === 'f' && c.n >= 4));
|
||||
console.log('PASS: two repeated migrations preserve all row counts; FK failure rolls back chat insert; foreign keys present.');
|
||||
console.log(JSON.stringify({ counts: before, constraints }));
|
||||
}
|
||||
main().catch(error => { console.error('FAIL: storage checks (' + (error.code || error.name) + ')'); process.exitCode = 1; }).finally(() => pool.end());
|
||||
Reference in New Issue
Block a user