This commit is contained in:
@@ -9,9 +9,6 @@ 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
|
||||
# --- Actual lab2 implementation (see REPORT.md) ---
|
||||
# APP_PORT is also the host port published on 127.0.0.1 by compose.yaml.
|
||||
# SESSION_STORE=postgres: sessions live in PostgreSQL; Valkey (CACHE_URL_FILE) caches lookups.
|
||||
SESSION_CACHE_MAX_SECONDS=300
|
||||
DB_POOL_MAX=10
|
||||
SHORT_TTL_PORT=8081
|
||||
|
||||
@@ -0,0 +1,526 @@
|
||||
# Демонстрация лабораторной 2 на защите
|
||||
|
||||
Сценарий повторяет раздел «Сценарий защиты» из README: стек поднимается с нуля на пустом volume, затем показываются сессии, сохранность после рестарта, роль Valkey, план SQL и отказы зависимостей.
|
||||
|
||||
**Важно:** выполняйте команды по порядку **в одном окне терминала**. Переменные `B`, `S`, `ALICE`, `BOB`, `CAROL`, `CHAT`, `TA`, `TB`, `TC` и функции `j`, `pg`, `vk` живут только в этом окне.
|
||||
|
||||
---
|
||||
|
||||
## 0. Подготовка: чистый clone
|
||||
|
||||
Если запущен рабочий стенд, останавливаем его. Volume при этом сохраняется, порт 8080 освобождается:
|
||||
|
||||
```bash
|
||||
(cd ~/Desktop/вуз/ВНП/lab2/mtusi2026lab2 && docker compose --profile ttl-test down)
|
||||
```
|
||||
|
||||
Скачиваем решение в новую папку:
|
||||
|
||||
```bash
|
||||
git clone -b solution/bvt2304-koshelev ssh://git@gitea.privcloud.tech:2222/Iicon18/mtusi2026lab2.git ~/Desktop/lab2-demo
|
||||
```
|
||||
|
||||
```bash
|
||||
cd ~/Desktop/lab2-demo
|
||||
```
|
||||
|
||||
Отдельное имя compose-проекта даёт отдельные контейнеры и **новый пустой volume**:
|
||||
|
||||
```bash
|
||||
export COMPOSE_PROJECT_NAME=lab2-demo
|
||||
```
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Если порт 8080 или 8081 занят, поменяйте `APP_PORT` / `SHORT_TTL_PORT` в `.env`, следующая команда сама подхватит новые значения.
|
||||
|
||||
```bash
|
||||
B=http://127.0.0.1:$(sed -n 's/^APP_PORT=//p' .env); S=http://127.0.0.1:$(sed -n 's/^SHORT_TTL_PORT=//p' .env); echo "$B $S"
|
||||
```
|
||||
|
||||
Вспомогательные функции: достать поле из JSON, выполнить SQL, выполнить команду Valkey.
|
||||
|
||||
```bash
|
||||
j() { python3 -c 'import sys,json;print(json.load(sys.stdin)[sys.argv[1]])' "$1"; }
|
||||
pg() { docker compose exec -T postgres psql -U messenger -d messenger -c "$1"; }
|
||||
vk() { docker compose exec -T valkey sh -c 'valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/valkey_conf)" "$@"' valkey-cli "$@"; }
|
||||
```
|
||||
|
||||
> **Сказать:** «Это свежий clone моей ветки в отдельный compose-проект, база будет пустой. `.env` и секреты не хранятся в Git, создаю их локально».
|
||||
|
||||
---
|
||||
|
||||
## 1. Секреты
|
||||
|
||||
```bash
|
||||
make secrets
|
||||
```
|
||||
|
||||
```bash
|
||||
ls -l secrets/
|
||||
```
|
||||
|
||||
```bash
|
||||
git check-ignore -v secrets/database_url .env
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «`scripts/init-secrets.sh` генерирует случайные пароли PostgreSQL и Valkey в папку `secrets/`. Она в `.gitignore`, поэтому в репозиторий не попадает».
|
||||
> - «В контейнеры пароли приходят как compose secrets, файлами в `/run/secrets/...`, а не переменными окружения. Поэтому их не видно в `docker inspect`».
|
||||
> - «Приложение читает `DATABASE_URL_FILE` и `CACHE_URL_FILE`, то есть путь к файлу, а не сам пароль».
|
||||
|
||||
---
|
||||
|
||||
## 2. Запуск стека и миграции
|
||||
|
||||
```bash
|
||||
cat compose.yaml
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «Четыре сервиса: `postgres` — источник истины, `valkey` — кэш сессий, `migrate` — одноразовый запуск миграций, `api` — приложение».
|
||||
> - «Версии образов закреплены: `postgres:17.6-alpine3.22`, `valkey/valkey:8.1.4-alpine3.22`; `latest` нигде нет».
|
||||
> - «`depends_on` с условиями: api стартует, только когда postgres `healthy`, а migrate завершился с кодом 0».
|
||||
> - «Данные PostgreSQL лежат в именованном volume `pgdata`».
|
||||
> - «Порт api опубликован только на `127.0.0.1`, порты БД и Valkey наружу не публикуются».
|
||||
|
||||
```bash
|
||||
make up
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose ps --all
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose logs migrate
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -si "$B/health/ready"
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «`make up` = `docker compose up -d --build --wait`, ждёт, пока healthcheck api станет healthy. Healthcheck api проверяет `/health/ready`, а readiness делает `SELECT 1` в PostgreSQL».
|
||||
> - «`migrate` в статусе `Exited (0)`: применил `0001_init` на пустую базу (`1 applied now, 0 before`)».
|
||||
|
||||
---
|
||||
|
||||
## 3. Схема БД
|
||||
|
||||
```bash
|
||||
pg '\dt'
|
||||
```
|
||||
|
||||
```bash
|
||||
pg '\d messages'
|
||||
```
|
||||
|
||||
```bash
|
||||
pg 'SELECT * FROM schema_migrations'
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «Таблицы `users`, `chats`, `chat_members`, `messages`, `sessions` и служебная `schema_migrations`, где записаны применённые миграции».
|
||||
> - «`UNIQUE(username)`, CHECK на формат и длины».
|
||||
> - «Внешний ключ `messages (chat_id, sender_id) → chat_members`: база сама не даст записать сообщение от не-участника».
|
||||
> - «Индекс `messages_chat_history_idx (chat_id, created_at, id)` повторяет запрос истории, обоснование в шаге 12».
|
||||
> - «Миграции версионируются. Раннер берёт `pg_advisory_lock` и пропускает уже применённые версии, поэтому повторный запуск безопасен».
|
||||
|
||||
---
|
||||
|
||||
## 4. Публичный тест
|
||||
|
||||
```bash
|
||||
make check
|
||||
```
|
||||
|
||||
```bash
|
||||
make test BASE_URL="$B"
|
||||
```
|
||||
|
||||
> **Сказать:** «Это публичный smoke-тест преподавателя для lab2: регистрация с паролем, вход через Basic, работа по Bearer, чаты, сообщения, пагинация, ошибки и logout».
|
||||
|
||||
---
|
||||
|
||||
## 5. Регистрация, вход, общий чат
|
||||
|
||||
Регистрация теперь требует `password` (12–128 символов):
|
||||
|
||||
```bash
|
||||
ALICE=$(curl -s -X POST "$B/api/v1/users" -H 'Content-Type: application/json' -d '{"username":"alice","display_name":"Алиса","password":"Alice-demo-pass-1"}' | tee /dev/stderr | j id)
|
||||
```
|
||||
|
||||
```bash
|
||||
BOB=$(curl -s -X POST "$B/api/v1/users" -H 'Content-Type: application/json' -d '{"username":"bob","display_name":"Боб 🚀","password":"Bob-demo-pass-123"}' | tee /dev/stderr | j id)
|
||||
```
|
||||
|
||||
```bash
|
||||
CAROL=$(curl -s -X POST "$B/api/v1/users" -H 'Content-Type: application/json' -d '{"username":"carol","display_name":"Кэрол","password":"Carol:with:colons"}' | tee /dev/stderr | j id)
|
||||
```
|
||||
|
||||
> **Сказать:** «В ответе нет ни пароля, ни хеша, только `id`, `username`, `display_name`, `created_at`. Время назначает PostgreSQL».
|
||||
|
||||
Пароль в базе хранится только как хеш:
|
||||
|
||||
```bash
|
||||
pg "SELECT username, left(password_hash, 40) AS hash FROM users WHERE username IN ('alice','bob','carol')"
|
||||
```
|
||||
|
||||
> **Сказать:** «Хеш Argon2id, строка начинается с `$argon2id$v=19$m=65536,t=3,p=4`: 64 МБ памяти и 3 прохода на одну проверку. Соль своя у каждого пароля, поэтому одинаковые пароли дают разные хеши».
|
||||
|
||||
Вход: Basic только на `POST /auth/sessions`. `curl -u` сам собирает заголовок `Authorization: Basic base64(username:password)`:
|
||||
|
||||
```bash
|
||||
curl -si -X POST -u 'carol:Carol:with:colons' "$B/api/v1/auth/sessions"
|
||||
```
|
||||
|
||||
```bash
|
||||
TA=$(curl -s -X POST -u 'alice:Alice-demo-pass-1' "$B/api/v1/auth/sessions" | j token); TB=$(curl -s -X POST -u 'bob:Bob-demo-pass-123' "$B/api/v1/auth/sessions" | j token); TC=$(curl -s -X POST -u 'carol:Carol:with:colons' "$B/api/v1/auth/sessions" | j token); echo "длина токена: ${#TA}"
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «Ответ 201: `token`, `token_type: Bearer`, `expires_at`, `user`. Двоеточие в пароле допустимо, потому что строка делится по **первому** `:`».
|
||||
> - «Токен — `secrets.token_urlsafe(32)`, 256 случайных бит. Он непрозрачный: внутри нет ни id, ни username, это не JWT».
|
||||
> - «Срок жизни из `SESSION_TTL_SECONDS` (по умолчанию 3600 с), `expires_at` считает база».
|
||||
|
||||
В базе лежит не сам токен, а его sha256:
|
||||
|
||||
```bash
|
||||
pg "SELECT encode(token_hash,'hex') AS token_hash, expires_at, revoked_at FROM sessions ORDER BY created_at DESC LIMIT 3"
|
||||
```
|
||||
|
||||
> **Сказать:** «Если украдут дамп БД, войти по нему не получится: из sha256 токен не восстановить. Медленный KDF для токена не нужен: он случайный, 2^256 вариантов не перебрать. Пароль же выбирает человек, его можно перебрать по словарю, поэтому для пароля нужен медленный Argon2id».
|
||||
|
||||
Алиса создаёт чат с Бобом, оба пишут:
|
||||
|
||||
```bash
|
||||
CHAT=$(curl -s -X POST "$B/api/v1/chats" -H 'Content-Type: application/json' -H "Authorization: Bearer $TA" -d "{\"title\":\"Проект по ВНП\",\"member_ids\":[\"$ALICE\",\"$BOB\"]}" | tee /dev/stderr | j id)
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$B/api/v1/chats/$CHAT/messages" -H 'Content-Type: application/json' -H "Authorization: Bearer $TA" -d '{"text":"Привет, Боб! 👋"}'
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -s -X POST "$B/api/v1/chats/$CHAT/messages" -H 'Content-Type: application/json' -H "Authorization: Bearer $TB" -d '{"text":"Привет, Алиса!"}'
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -s "$B/api/v1/chats/$CHAT/messages" -H "Authorization: Bearer $TB" | python3 -m json.tool --no-ensure-ascii
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «Чат и участники создаются **одной транзакцией**. Если участник неизвестен, FK срабатывает внутри транзакции, вставка чата откатывается и клиент получает 400. Полупустого чата не остаётся (проверяет `db_integrity_test.py`)».
|
||||
> - «`sender_id` сервер берёт из сессии. Сообщение вставляется одним запросом `INSERT … WHERE EXISTS (участник)`: проверка доступа и запись атомарны».
|
||||
|
||||
Кэрол аутентифицирована, но не участник чата:
|
||||
|
||||
```bash
|
||||
curl -i "$B/api/v1/chats/$CHAT/messages" -H "Authorization: Bearer $TC"
|
||||
```
|
||||
|
||||
> **Сказать:** «Аутентификация отвечает на вопрос "кто ты": токен Кэрол валиден. Доступ отвечает на вопрос "можно ли тебе в этот чат": нельзя, поэтому 404, а не 403, чтобы не раскрывать, что такой чат существует».
|
||||
|
||||
---
|
||||
|
||||
## 6. Ошибки аутентификации
|
||||
|
||||
Неверный пароль и несуществующий пользователь дают одинаковый 401 с вызовом `Basic`:
|
||||
|
||||
```bash
|
||||
curl -i -X POST -u 'alice:wrong-password-1' "$B/api/v1/auth/sessions"
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -i -X POST -u 'nobody:wrong-password-1' "$B/api/v1/auth/sessions"
|
||||
```
|
||||
|
||||
> **Сказать:** «Ответы одинаковые, поэтому подобрать существующие username не выйдет. Для несуществующего пользователя всё равно проверяется фиктивный хеш, чтобы время ответа тоже было одинаковым».
|
||||
|
||||
Basic на бизнес-endpoint даёт 401 с вызовом `Bearer`:
|
||||
|
||||
```bash
|
||||
curl -i -u 'alice:Alice-demo-pass-1' "$B/api/v1/users/me"
|
||||
```
|
||||
|
||||
`X-User-Id` из lab1 больше ничего не значит:
|
||||
|
||||
```bash
|
||||
curl -i "$B/api/v1/users/me" -H "X-User-Id: $ALICE"
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -s "$B/api/v1/users/me" -H "Authorization: Bearer $TC" -H "X-User-Id: $ALICE"
|
||||
```
|
||||
|
||||
> **Сказать:** «Без токена `X-User-Id` даёт 401. С токеном Кэрол и `X-User-Id` Алисы ответ — Кэрол: заголовок просто игнорируется».
|
||||
|
||||
Короткий пароль при регистрации даёт 400:
|
||||
|
||||
```bash
|
||||
curl -i -X POST "$B/api/v1/users" -H 'Content-Type: application/json' -d '{"username":"dave","display_name":"Дэйв","password":"short"}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Роль Valkey: кэш сессий
|
||||
|
||||
Все ключи сессий: сколько секунд осталось жить и значение.
|
||||
|
||||
```bash
|
||||
for k in $(vk --scan --pattern 'session:*'); do echo "$(vk TTL "$k")s $(vk GET "$k" | cut -c1-70)"; done
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «Строки `{"user": …}` — закэшированные живые сессии. Строки `revoked` — tombstone'ы после logout, например от smoke-теста в шаге 4 (подробно в шаге 9)».
|
||||
> - «**Источник истины — PostgreSQL**. Valkey только кэширует проверку токена, чтобы не ходить в БД на каждом запросе. `/users/me` вообще обслуживается из кэша».
|
||||
> - «Ключ — `session:` + sha256 токена, значение — пользователь и `expires_at`».
|
||||
> - «TTL записи = min(остаток сессии, 300 с). При чтении из кэша `expires_at` сравнивается ещё раз, поэтому просроченная сессия из кэша не пройдёт».
|
||||
> - «Persistence у Valkey выключена (`save ""`, `appendonly no`). После flush или рестарта кэш просто пуст: следующий запрос проверит токен в PostgreSQL и снова положит его в кэш. Данные при этом не теряются».
|
||||
|
||||
---
|
||||
|
||||
## 8. Сохранность: рестарт API и всех хранилищ
|
||||
|
||||
```bash
|
||||
cat scripts/restart.sh
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose ps --format 'table {{.Service}}\t{{.Status}}'
|
||||
```
|
||||
|
||||
```bash
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL="$B"
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose ps --format 'table {{.Service}}\t{{.Status}}'
|
||||
```
|
||||
|
||||
> **Сказать:** «Тест держит токен только в памяти, вызывает мой `restart.sh` (остановить api, valkey и postgres, затем поднять заново, volume не трогается) и тем же токеном читает те же данные. По `Up N seconds` видно, что все три контейнера действительно перезапускались».
|
||||
|
||||
Проверим руками тем же токеном Алисы:
|
||||
|
||||
```bash
|
||||
vk DBSIZE
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -s "$B/api/v1/chats/$CHAT/messages" -H "Authorization: Bearer $TA" | python3 -m json.tool --no-ensure-ascii
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose logs migrate | tail -1
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «Прежний токен работает, сообщения на месте. Сессия пережила рестарт, потому что хранится в PostgreSQL. Срок не продлился: `expires_at` записан в базе».
|
||||
> - «Старые записи кэша пропали вместе с рестартом Valkey. Те несколько ключей, что видны в `DBSIZE`, заново положили проверочные запросы теста после рестарта: кэш наполняется сам из PostgreSQL».
|
||||
> - «Миграции при рестарте прогнались ещё раз: `0 applied now, 1 before`, без дублирования».
|
||||
> - «Ответ на вопрос "что подтверждает COMMIT": запись попала в WAL и сброшена на диск (`fsync=on`, `synchronous_commit=on` по умолчанию). Поэтому 201 после COMMIT означает, что сообщение переживёт и падение PostgreSQL. Если выключить `synchronous_commit`, последние подтверждённые транзакции можно потерять».
|
||||
|
||||
---
|
||||
|
||||
## 9. Logout
|
||||
|
||||
```bash
|
||||
curl -i -X DELETE "$B/api/v1/auth/sessions/current" -H "Authorization: Bearer $TC"
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -i "$B/api/v1/users/me" -H "Authorization: Bearer $TC"
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -i -X DELETE "$B/api/v1/auth/sessions/current" -H "Authorization: Bearer $TC"
|
||||
```
|
||||
|
||||
```bash
|
||||
for k in $(vk --scan --pattern 'session:*'); do echo "$k => $(vk GET "$k" | cut -c1-40)"; done
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «Logout даёт 204 без тела. После него тот же токен получает 401, повторный logout тоже 401».
|
||||
> - «Порядок такой: сначала `revoked_at` в PostgreSQL (источник истины), потом в Valkey пишется **tombstone** `revoked`, а не простое удаление ключа».
|
||||
> - «Зачем tombstone: параллельный запрос мог прочитать сессию из БД **до** logout и положить её в кэш **после**. Кэш заполняется через `SET NX` и не перезапишет tombstone, поэтому отозванная сессия не воскреснет».
|
||||
|
||||
---
|
||||
|
||||
## 10. Истечение сессии (короткий TTL)
|
||||
|
||||
Поднимаем второй экземпляр того же образа с `SESSION_TTL_SECONDS=2`:
|
||||
|
||||
```bash
|
||||
docker compose --profile ttl-test up -d --wait api-short-ttl
|
||||
```
|
||||
|
||||
Вход и обе проверки одной строкой: окно в 2 секунды слишком короткое, чтобы успеть вставить отдельные команды.
|
||||
|
||||
```bash
|
||||
TD=$(curl -s -X POST -u 'bob:Bob-demo-pass-123' "$S/api/v1/auth/sessions" | tee /dev/stderr | j token); echo; curl -s -o /dev/null -w 'сразу: %{http_code}\n' "$S/api/v1/users/me" -H "Authorization: Bearer $TD"; sleep 3; curl -si "$S/api/v1/users/me" -H "Authorization: Bearer $TD"
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose --profile ttl-test stop api-short-ttl
|
||||
```
|
||||
|
||||
> **Сказать:** «`expires_at` всего через 2 секунды после входа. Сразу 200, через 3 секунды 401 с `WWW-Authenticate: Bearer`, хотя запись была и в кэше. Обычный api работает с TTL 3600, так как smoke требует не меньше 300».
|
||||
|
||||
---
|
||||
|
||||
## 11. Отказы зависимостей
|
||||
|
||||
### Valkey недоступен — API работает без кэша
|
||||
|
||||
```bash
|
||||
docker compose stop valkey
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -si "$B/health/ready"
|
||||
```
|
||||
|
||||
```bash
|
||||
time curl -s "$B/api/v1/users/me" -H "Authorization: Bearer $TA"
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w '%{http_code}\n' "$B/api/v1/users/me" -H "Authorization: Bearer $TC"
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose logs --tail 3 api
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose start valkey
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «Readiness 200: Valkey для API не критичен».
|
||||
> - «Запросы идут напрямую в PostgreSQL, ответ за миллисекунды. Остановленный контейнер сразу отказывает в соединении. Если бы сеть зависла, сработал бы таймаут 0.3 с. После первой ошибки circuit breaker 5 секунд вообще не обращается к Valkey, поэтому задержка не копится. В логе предупреждение `bypassing cache`».
|
||||
> - «Отозванный токен Кэрол по-прежнему 401: отзыв записан в БД».
|
||||
|
||||
### PostgreSQL недоступен — ограниченная ошибка, анонимного доступа нет
|
||||
|
||||
Заранее берём новый токен Боба. Проверок по нему ещё не было, поэтому в кэше его нет:
|
||||
|
||||
```bash
|
||||
TB2=$(curl -s -X POST -u 'bob:Bob-demo-pass-123' "$B/api/v1/auth/sessions" | j token)
|
||||
```
|
||||
|
||||
```bash
|
||||
docker compose stop postgres
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -si "$B/health/live"; echo; curl -si "$B/health/ready"
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -si "$B/api/v1/chats" -H "Authorization: Bearer $TA"
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -s -o /dev/null -w '%{http_code}\n' "$B/api/v1/users/me" -H "Authorization: Bearer $TB2"; curl -s -o /dev/null -w '%{http_code}\n' "$B/api/v1/users/me"
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «Liveness 200: процесс жив. Readiness 503: обслуживать запросы безопасно нельзя».
|
||||
> - «Бизнес-запрос даёт `503 unavailable` мгновенно, без SQL и стектрейсов в теле. Pool ограничен 10 соединениями, таймауты подключения, захвата соединения и команды — 3, 3 и 5 с, так что зависнуть запрос не может».
|
||||
> - «Токен, который проверить негде (в кэше его нет, БД лежит), получает **503, а не 200**: непроверенный запрос не считается аутентифицированным. Без токена — по-прежнему 401».
|
||||
|
||||
```bash
|
||||
docker compose start postgres
|
||||
```
|
||||
|
||||
```bash
|
||||
until curl -s -o /dev/null -w '%{http_code}' "$B/health/ready" | grep -q 200; do sleep 0.5; done; echo ready
|
||||
```
|
||||
|
||||
```bash
|
||||
curl -s "$B/api/v1/users/me" -H "Authorization: Bearer $TB2"
|
||||
```
|
||||
|
||||
> **Сказать:** «API восстановился сам, без своего рестарта: pool переподключается к базе по требованию».
|
||||
|
||||
---
|
||||
|
||||
## 12. Индекс истории и EXPLAIN
|
||||
|
||||
```bash
|
||||
make explain
|
||||
```
|
||||
|
||||
```bash
|
||||
cat evidence/explain_history.txt
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - «Скрипт засевает 70 000 синтетических сообщений, 20 000 из них в одном чате, и выполняет **тот же запрос, что в коде**, как prepared statement: `WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT 51`».
|
||||
> - «С индексом `(chat_id, created_at, id)`: `Index Scan`, условие по курсору уходит прямо в `Index Cond`, читается 4 буфера, около 0.03 мс. Даже на глубокой странице после 15 000-го сообщения работа та же».
|
||||
> - «Без индекса (DROP INDEX внутри транзакции и ROLLBACK): `Seq Scan` по всей таблице и `Sort`, 940 буферов, 3–4 мс, и время растёт вместе с таблицей».
|
||||
> - «Keyset против OFFSET: `OFFSET 15000` заставил бы прочитать и выбросить 15 000 строк на каждой странице. Курсор сразу прыгает в нужное место индекса».
|
||||
|
||||
---
|
||||
|
||||
## 13. Уровень 4: свои тесты одной командой
|
||||
|
||||
```bash
|
||||
make test-student BASE_URL="$B" SHORT_TTL_URL="$S"
|
||||
```
|
||||
|
||||
> **Сказать:**
|
||||
> - **own_tests.py**, **concurrency_test.py** — перенесены из lab1: битый JSON, чужой чат, пустое сообщение, пагинация; 100 параллельных сообщений от 10 клиентов.
|
||||
> - **auth_test.py** — неверный пароль, Basic и `X-User-Id` на бизнес-endpoint, пароль с `:` и UTF-8, logout только текущего токена, истечение при TTL=2 с.
|
||||
> - **db_integrity_test.py**:
|
||||
> - 20 параллельных регистраций одного username → ровно один 201 и девятнадцать 409. Гонку решает `UNIQUE` в БД, а не проверка "SELECT, потом INSERT";
|
||||
> - rollback создания чата;
|
||||
> - Argon2id в базе;
|
||||
> - повторные миграции ничего не меняют.
|
||||
> - **dependency_test.py** — роль Valkey (кэш, TTL, tombstone), остановка Valkey, остановка PostgreSQL и восстановление.
|
||||
> - **sigterm_test.sh** — `docker compose stop api` → код выхода 0, а не 137.
|
||||
|
||||
---
|
||||
|
||||
## 14. Остановка и удаление данных
|
||||
|
||||
Обычная остановка: данные остаются в volume.
|
||||
|
||||
```bash
|
||||
docker compose --profile ttl-test down
|
||||
```
|
||||
|
||||
```bash
|
||||
docker volume ls | grep lab2-demo
|
||||
```
|
||||
|
||||
Намеренное удаление учебных данных демо-стенда (необратимо):
|
||||
|
||||
```bash
|
||||
docker compose --profile ttl-test down -v
|
||||
```
|
||||
|
||||
> **Сказать:** «`down` удаляет контейнеры, но не volume, поэтому данные переживут и это. Только `down -v` удаляет volume. В `restart.sh` и тестах `-v` не используется нигде».
|
||||
|
||||
---
|
||||
|
||||
## Короткие ответы на вопросы из README
|
||||
|
||||
- **Что подтверждает COMMIT и от чего зависят гарантии.**
|
||||
- COMMIT значит, что транзакция записана в WAL и, при `synchronous_commit=on` и `fsync=on` (по умолчанию), сброшена на диск. Такая запись переживает падение процесса и рестарт ОС.
|
||||
- С `synchronous_commit=off` последние подтверждённые транзакции можно потерять. С `fsync=off` после сбоя питания можно повредить базу.
|
||||
- Потерю самого диска или хоста COMMIT не покрывает: нужны реплики и бэкапы.
|
||||
- **Где хранятся сессии и что будет после flush или рестарта Redis.**
|
||||
- Сессии хранятся в PostgreSQL, в таблице `sessions` (`sha256(token)`, `expires_at`, `revoked_at`). Valkey только кэш.
|
||||
- После flush кэш пуст, первая проверка токена идёт в БД. Ни одна сессия не теряется и не воскрешается: отзыв тоже записан в БД. Поэтому persistence у Valkey не нужна.
|
||||
- **Аутентификация против доступа к чату.**
|
||||
- Аутентификация устанавливает, кто ты: валидный Bearer-токен, иначе 401.
|
||||
- Доступ (авторизация) решает, можно ли этому пользователю к этому ресурсу: участник ли он чата. Если нет — 404, а не 403, чтобы не раскрывать существование чата.
|
||||
- **Hash пароля против быстрого checksum.**
|
||||
- Быстрый хеш (sha256) нужен для целостности и для индексации случайных значений: так мы храним токены.
|
||||
- Пароль низкоэнтропийный, его подбирают по словарю. Для него нужен медленный KDF с солью и затратами памяти (Argon2id), чтобы каждая попытка подбора была дорогой даже на GPU.
|
||||
@@ -25,7 +25,6 @@ test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
# --- Student implementation helpers (see REPORT.md) ---
|
||||
secrets:
|
||||
sh scripts/init-secrets.sh
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
| valkey | `valkey/valkey:8.1.4-alpine3.22` | Valkey 8.1.4 |
|
||||
|
||||
```sh
|
||||
cp .env.example .env # при занятом 8080 поменять APP_PORT (у автора 18080)
|
||||
cp .env.example .env # при занятом 8080 поменять APP_PORT
|
||||
make secrets # scripts/init-secrets.sh: случайные пароли в ./secrets (в .gitignore)
|
||||
docker compose --env-file .env config --quiet
|
||||
make up # docker compose up -d --build --wait: postgres -> migrate -> api; ждёт healthcheck /health/ready
|
||||
@@ -102,7 +102,7 @@ migrate (one-shot) ──> postgres : применение migrations/*.sql
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
Все файлы в `evidence/` сняты 2026-10-07 на MacBook (Apple Silicon, Docker Desktop, без CPU/RAM-лимитов в compose). Порт стенда автора — 18080, потому что 8080 занят другим проектом.
|
||||
Файлы в `evidence/` сняты 2026-10-07 (explain_history) и 2026-10-08 UTC (остальные) на MacBook (Apple Silicon, Docker Desktop, без CPU/RAM-лимитов в compose).
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
|
||||
+3
-13
@@ -1,4 +1,3 @@
|
||||
"""Passwords (Argon2id), Basic login and opaque Bearer sessions."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -18,10 +17,8 @@ from app.cache import REVOKED, SessionCache
|
||||
from app.errors import BASIC_CHALLENGE, unauthorized
|
||||
from app.storage import Store, fmt_ts, user_row
|
||||
|
||||
# argon2-cffi defaults = RFC 9106 low-memory profile (Argon2id, t=3, m=64 MiB, p=4).
|
||||
_hasher = PasswordHasher()
|
||||
_hash_slots = asyncio.Semaphore(config.PASSWORD_HASH_CONCURRENCY)
|
||||
# Verified when the username does not exist, so both failures cost the same time.
|
||||
_DUMMY_HASH = _hasher.hash("dummy-password-for-timing")
|
||||
|
||||
|
||||
@@ -42,8 +39,6 @@ async def verify_password(password_hash: str, password: str) -> bool:
|
||||
|
||||
|
||||
def token_digest(token: str) -> bytes:
|
||||
# A fast hash is enough here: the token already carries 256 random bits,
|
||||
# unlike a human password that needs a slow KDF against guessing.
|
||||
return hashlib.sha256(token.encode("ascii")).digest()
|
||||
|
||||
|
||||
@@ -58,7 +53,7 @@ def parse_basic(header: Optional[str]) -> Tuple[str, str]:
|
||||
decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
raise bad from None
|
||||
username, sep, password = decoded.partition(":") # the password may contain ':'
|
||||
username, sep, password = decoded.partition(":")
|
||||
if not sep or not username.isascii() or not 12 <= len(password) <= 128:
|
||||
raise bad
|
||||
return username, password
|
||||
@@ -82,16 +77,12 @@ async def login(store: Store, header: Optional[str]) -> dict:
|
||||
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
|
||||
if not await verify_password(row["password_hash"], password):
|
||||
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
|
||||
token = secrets.token_urlsafe(32) # 256 bits of entropy
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = await store.create_session(token_digest(token), row["id"], config.SESSION_TTL_SECONDS)
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": fmt_ts(expires_at), "user": user_row(row)}
|
||||
|
||||
|
||||
async def authenticate(store: Store, cache: SessionCache, header: Optional[str]) -> dict:
|
||||
"""Return the session's user or raise 401. Cache first, PostgreSQL on a miss.
|
||||
|
||||
If PostgreSQL is down and the cache has no answer the error propagates as 503:
|
||||
an unverifiable token is never treated as authenticated."""
|
||||
digest = token_digest(parse_bearer(header))
|
||||
cached = await cache.get(digest)
|
||||
if cached == REVOKED:
|
||||
@@ -112,10 +103,9 @@ async def authenticate(store: Store, cache: SessionCache, header: Optional[str])
|
||||
|
||||
|
||||
async def logout(store: Store, cache: SessionCache, header: Optional[str]) -> None:
|
||||
# Authenticate first so an already revoked token gets 401, as the contract requires.
|
||||
await authenticate(store, cache, header)
|
||||
digest = token_digest(parse_bearer(header))
|
||||
expires_at = await store.revoke_session(digest) # PostgreSQL first: it is the truth
|
||||
expires_at = await store.revoke_session(digest)
|
||||
if expires_at is None:
|
||||
raise unauthorized("session expired or revoked")
|
||||
remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds()) + 1
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
"""Valkey session cache. Never the source of truth: every failure degrades to a miss.
|
||||
|
||||
Keys: session:<sha256(token) hex>
|
||||
Value: JSON {"user": {...}, "expires_at": "..."} - a valid session
|
||||
"revoked" - tombstone written by logout
|
||||
Entry TTL = min(time left in the session, SESSION_CACHE_MAX_SECONDS).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
@@ -45,7 +38,6 @@ class SessionCache:
|
||||
return self._client is not None and time.monotonic() >= self._down_until
|
||||
|
||||
def _failed(self, op: str, exc: Exception) -> None:
|
||||
# Circuit breaker: one slow failure, then skip the cache for a few seconds.
|
||||
self._down_until = time.monotonic() + config.CACHE_RETRY_AFTER
|
||||
logger.warning("cache %s failed (%s); bypassing cache for %.0fs", op, type(exc).__name__, config.CACHE_RETRY_AFTER)
|
||||
|
||||
@@ -69,7 +61,6 @@ class SessionCache:
|
||||
return None
|
||||
|
||||
async def put(self, token_hash: bytes, entry: dict, ttl_seconds: int) -> None:
|
||||
"""Fill after a PostgreSQL read. NX: never overwrite a logout tombstone."""
|
||||
ttl = min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)
|
||||
if ttl <= 0 or not self._usable():
|
||||
return
|
||||
@@ -79,9 +70,6 @@ class SessionCache:
|
||||
self._failed("set", exc)
|
||||
|
||||
async def revoke(self, token_hash: bytes, ttl_seconds: int) -> None:
|
||||
"""Tombstone instead of DEL: a concurrent fill that read PostgreSQL before the
|
||||
revoke cannot re-insert the session afterwards (its SET NX loses).
|
||||
Tried even while the breaker is open: logout is rare and correctness matters more."""
|
||||
if self._client is None:
|
||||
return
|
||||
try:
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Runtime configuration from environment; secrets are read from *_FILE paths."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
@@ -6,7 +5,6 @@ from typing import Optional
|
||||
|
||||
|
||||
def _secret(name: str) -> Optional[str]:
|
||||
"""NAME wins over NAME_FILE; NAME_FILE keeps the value out of `docker inspect`."""
|
||||
value = os.environ.get(name)
|
||||
if value:
|
||||
return value.strip()
|
||||
@@ -29,7 +27,6 @@ DATABASE_URL = _secret("DATABASE_URL")
|
||||
CACHE_URL = _secret("CACHE_URL")
|
||||
|
||||
SESSION_TTL_SECONDS = _int("SESSION_TTL_SECONDS", 3600)
|
||||
# Upper bound for one cached session entry; PostgreSQL is re-checked after it.
|
||||
SESSION_CACHE_MAX_SECONDS = _int("SESSION_CACHE_MAX_SECONDS", 300)
|
||||
|
||||
DB_POOL_MAX = _int("DB_POOL_MAX", 10)
|
||||
@@ -39,8 +36,6 @@ DB_COMMAND_TIMEOUT = _float("DB_COMMAND_TIMEOUT", 5)
|
||||
|
||||
CACHE_TIMEOUT = _float("CACHE_TIMEOUT", 0.3)
|
||||
CACHE_POOL_MAX = _int("CACHE_POOL_MAX", 20)
|
||||
# After a cache error, skip the cache for this long instead of paying the timeout per request.
|
||||
CACHE_RETRY_AFTER = _float("CACHE_RETRY_AFTER", 5)
|
||||
|
||||
# Argon2id hashing is CPU/RAM heavy: bound how many run at once.
|
||||
PASSWORD_HASH_CONCURRENCY = _int("PASSWORD_HASH_CONCURRENCY", 4)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""API error type shared by all layers."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, Optional
|
||||
|
||||
+3
-34
@@ -1,4 +1,3 @@
|
||||
"""Lab 2: messenger API on PostgreSQL with Bearer sessions and a Valkey session cache."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
@@ -39,18 +38,13 @@ async def lifespan(_app: FastAPI):
|
||||
app = FastAPI(title="MTUSI Messenger — lab2", lifespan=lifespan)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cross-cutting: request id + uniform error envelope
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# PostgreSQL unreachable, restarting or pool exhausted -> bounded 503, never a hang.
|
||||
DB_UNAVAILABLE = (
|
||||
OSError, # includes ConnectionRefusedError and TimeoutError (pool acquire / connect)
|
||||
OSError,
|
||||
asyncpg.PostgresConnectionError,
|
||||
asyncpg.InterfaceError,
|
||||
asyncpg.TooManyConnectionsError,
|
||||
asyncpg.exceptions.OperatorInterventionError, # admin shutdown, cannot connect now
|
||||
asyncpg.exceptions.QueryCanceledError, # statement timeout
|
||||
asyncpg.exceptions.OperatorInterventionError,
|
||||
asyncpg.exceptions.QueryCanceledError,
|
||||
)
|
||||
|
||||
|
||||
@@ -70,8 +64,6 @@ async def request_id_middleware(request: Request, call_next):
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
# Unhandled errors must be answered here: Starlette's own 500 handler runs
|
||||
# outside this middleware and would drop the X-Request-Id header.
|
||||
logger.exception("unhandled error for request_id=%s", request_id)
|
||||
response = JSONResponse(status_code=500, content=error_body("internal_error", "internal error", request_id))
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
@@ -104,11 +96,6 @@ for _exc in DB_UNAVAILABLE:
|
||||
app.add_exception_handler(_exc, db_unavailable_handler)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Auth: Basic only on POST /auth/sessions, Bearer everywhere else.
|
||||
# X-User-Id is ignored since lab2.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def current_user(request: Request) -> dict:
|
||||
return await auth.authenticate(store, cache, request.headers.get("Authorization"))
|
||||
|
||||
@@ -124,10 +111,6 @@ def not_found() -> ApiError:
|
||||
return ApiError(404, "not_found", "chat not found")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Health
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.get("/health/live", response_model=Health)
|
||||
async def liveness():
|
||||
return Health()
|
||||
@@ -135,7 +118,6 @@ async def liveness():
|
||||
|
||||
@app.get("/health/ready", response_model=Health)
|
||||
async def readiness():
|
||||
# PostgreSQL is critical; Valkey is not (the API bypasses the cache without it).
|
||||
try:
|
||||
await store.ping()
|
||||
except DB_UNAVAILABLE:
|
||||
@@ -143,10 +125,6 @@ async def readiness():
|
||||
return Health()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Users and sessions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/v1/users", response_model=User, status_code=201)
|
||||
async def register_user(body: CreateUser):
|
||||
if not body.display_name.strip() or not body.password.strip():
|
||||
@@ -171,10 +149,6 @@ async def delete_session(request: Request):
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Chats
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
|
||||
async def create_chat(body: CreateChat, user: dict = Depends(current_user)):
|
||||
if not body.title.strip():
|
||||
@@ -203,15 +177,10 @@ async def get_chat(chat_id: str, user: dict = Depends(current_user)):
|
||||
return chat
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Messages
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
async def create_message(chat_id: str, body: CreateMessage, user: dict = Depends(current_user)):
|
||||
chat_uuid = parse_uuid(chat_id, "chat_id")
|
||||
if not body.text.strip():
|
||||
# Access is checked before content: an outsider gets 404 even for a blank text.
|
||||
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
|
||||
raise not_found()
|
||||
raise ApiError(400, "invalid_request", "text must not be blank")
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
"""Apply versioned SQL migrations from migrations/; safe to run repeatedly and concurrently.
|
||||
|
||||
Usage: python -m app.migrate
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
@@ -17,7 +13,6 @@ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(messag
|
||||
logger = logging.getLogger("migrate")
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"
|
||||
# Arbitrary constant: serialises concurrent runners (e.g. several API replicas in lab3).
|
||||
LOCK_ID = 2026_0002
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Pydantic request/response schemas mirroring contracts/openapi.json."""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
+1
-25
@@ -1,4 +1,3 @@
|
||||
"""PostgreSQL repository. Every query is parameterised; PostgreSQL is the source of truth."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
@@ -14,7 +13,6 @@ from app.errors import ApiError
|
||||
|
||||
|
||||
def fmt_ts(value: datetime) -> str:
|
||||
# Always 6 fractional digits: exact round trip with PostgreSQL microseconds.
|
||||
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
@@ -46,10 +44,6 @@ def message_row(row: asyncpg.Record) -> dict:
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Opaque keyset cursor bound to one resource
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def encode_cursor(resource: str, created_at: str, item_id: str) -> str:
|
||||
payload = json.dumps({"r": resource, "t": created_at, "i": item_id}, separators=(",", ":"))
|
||||
return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
@@ -65,12 +59,11 @@ def decode_cursor(resource: str, cursor: str) -> Tuple[datetime, uuid.UUID]:
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError("cursor time has no timezone")
|
||||
return created_at, uuid.UUID(payload["i"])
|
||||
except Exception as exc: # noqa: BLE001 - any malformed cursor is a 400
|
||||
except Exception as exc:
|
||||
raise ApiError(400, "invalid_request", "invalid cursor") from exc
|
||||
|
||||
|
||||
def page_of(items: List[dict], resource: str, limit: int) -> dict:
|
||||
"""Queries fetch limit+1 rows: the extra row only tells whether a next page exists."""
|
||||
page = items[:limit]
|
||||
next_cursor = None
|
||||
if len(items) > limit:
|
||||
@@ -79,17 +72,11 @@ def page_of(items: List[dict], resource: str, limit: int) -> dict:
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Repository
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class Store:
|
||||
def __init__(self):
|
||||
self.pool: Optional[asyncpg.Pool] = None
|
||||
|
||||
async def open(self) -> None:
|
||||
# min_size=0: connections open on demand, so the API starts even while
|
||||
# PostgreSQL is down and readiness reports 503 until it is back.
|
||||
self.pool = await asyncpg.create_pool(
|
||||
config.DATABASE_URL,
|
||||
min_size=0,
|
||||
@@ -110,7 +97,6 @@ class Store:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchval("SELECT 1") == 1
|
||||
|
||||
# -- users --------------------------------------------------------------
|
||||
|
||||
async def create_user(self, username: str, display_name: str, password_hash: str) -> dict:
|
||||
async with self.acquire() as conn:
|
||||
@@ -124,7 +110,6 @@ class Store:
|
||||
uuid.uuid4(), username, display_name, password_hash,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
# The UNIQUE constraint, not a prior SELECT, decides concurrent registrations.
|
||||
raise ApiError(409, "conflict", "username already taken") from None
|
||||
return user_row(row)
|
||||
|
||||
@@ -135,7 +120,6 @@ class Store:
|
||||
username,
|
||||
)
|
||||
|
||||
# -- sessions -----------------------------------------------------------
|
||||
|
||||
async def create_session(self, token_hash: bytes, user_id: uuid.UUID, ttl_seconds: int) -> datetime:
|
||||
async with self.acquire() as conn:
|
||||
@@ -149,7 +133,6 @@ class Store:
|
||||
)
|
||||
|
||||
async def find_session(self, token_hash: bytes) -> Optional[asyncpg.Record]:
|
||||
"""Only a live session: not revoked and not expired by the database clock."""
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchrow(
|
||||
"""
|
||||
@@ -171,13 +154,8 @@ class Store:
|
||||
token_hash,
|
||||
)
|
||||
|
||||
# -- chats --------------------------------------------------------------
|
||||
|
||||
async def create_chat(self, title: str, member_ids: List[uuid.UUID]) -> dict:
|
||||
"""Chat and all memberships commit together or not at all.
|
||||
|
||||
Unknown members are detected by the foreign key inside the transaction, so a
|
||||
failure after the chat row was inserted really exercises the rollback."""
|
||||
chat_id = uuid.uuid4()
|
||||
async with self.acquire() as conn:
|
||||
try:
|
||||
@@ -245,10 +223,8 @@ class Store:
|
||||
chat_id, user_id,
|
||||
))
|
||||
|
||||
# -- messages -----------------------------------------------------------
|
||||
|
||||
async def create_message(self, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str) -> Optional[dict]:
|
||||
"""Membership check and insert in one statement; None means "no such chat for you"."""
|
||||
async with self.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
# Lab 2 stack: api -> postgres (source of truth) + valkey (session cache).
|
||||
# Prepare secrets first: scripts/init-secrets.sh. Start: docker compose up -d --build --wait
|
||||
name: messenger-lab2
|
||||
|
||||
x-api: &api
|
||||
@@ -20,7 +18,6 @@ x-api: &api
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
valkey:
|
||||
# The cache is optional for correctness: only wait for the container to start.
|
||||
condition: service_started
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
@@ -47,11 +44,9 @@ services:
|
||||
|
||||
valkey:
|
||||
image: valkey/valkey:8.1.4-alpine3.22
|
||||
# requirepass and cache-only settings live in the secret config file.
|
||||
command: ["valkey-server", "/run/secrets/valkey_conf"]
|
||||
secrets: [valkey_conf]
|
||||
healthcheck:
|
||||
# NOAUTH also proves the server answers; the password stays out of the process list.
|
||||
test: ["CMD-SHELL", "valkey-cli ping 2>&1 | grep -qE 'PONG|NOAUTH'"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
@@ -75,8 +70,6 @@ services:
|
||||
ports:
|
||||
- "127.0.0.1:${APP_PORT:-8080}:8080"
|
||||
|
||||
# Same image with a 2-second TTL, only for the expiry test:
|
||||
# docker compose --profile ttl-test up -d --wait api-short-ttl
|
||||
api-short-ttl:
|
||||
<<: *api
|
||||
profiles: [ttl-test]
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
# EXPLAIN evidence for message history pagination
|
||||
# date: 2026-10-07T14:17:55Z commit: 65003b6
|
||||
# date: 2026-10-09T09:35:29Z commit: e914e38
|
||||
# postgres: 17.6
|
||||
# messages total: 70112, in measured chat: 20000
|
||||
# messages total: 70006, in measured chat: 20000
|
||||
|
||||
PREPARE
|
||||
PREPARE
|
||||
=== 1. WITH index messages_chat_history_idx: first page (limit 50 + 1) ===
|
||||
QUERY PLAN
|
||||
---------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=0.42..8.60 rows=51 width=78) (actual time=0.014..0.019 rows=51 loops=1)
|
||||
Limit (cost=0.42..7.37 rows=51 width=78) (actual time=0.017..0.022 rows=51 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_chat_history_idx on messages (cost=0.42..3227.11 rows=20122 width=78) (actual time=0.013..0.015 rows=51 loops=1)
|
||||
-> Index Scan using messages_chat_history_idx on messages (cost=0.42..2712.54 rows=19884 width=78) (actual time=0.016..0.019 rows=51 loops=1)
|
||||
Index Cond: (chat_id = '00000000-0000-4000-8000-000000000100'::uuid)
|
||||
Buffers: shared hit=4
|
||||
Planning:
|
||||
Buffers: shared hit=106
|
||||
Planning Time: 0.272 ms
|
||||
Execution Time: 0.031 ms
|
||||
Planning Time: 0.287 ms
|
||||
Execution Time: 0.035 ms
|
||||
(9 rows)
|
||||
|
||||
=== 2. WITH index: deep page, cursor after message #15000 of 20000 ===
|
||||
QUERY PLAN
|
||||
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=0.42..55.74 rows=51 width=78) (actual time=0.012..0.017 rows=51 loops=1)
|
||||
Limit (cost=0.42..54.50 rows=51 width=78) (actual time=0.016..0.021 rows=51 loops=1)
|
||||
Buffers: shared hit=4
|
||||
-> Index Scan using messages_chat_history_idx on messages (cost=0.42..1590.70 rows=1466 width=78) (actual time=0.012..0.014 rows=51 loops=1)
|
||||
-> Index Scan using messages_chat_history_idx on messages (cost=0.42..1492.33 rows=1407 width=78) (actual time=0.016..0.019 rows=51 loops=1)
|
||||
Index Cond: ((chat_id = '00000000-0000-4000-8000-000000000100'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 04:10:00+00'::timestamp with time zone, '47ba2a9c-d238-4807-2008-6ea72cb0f95c'::uuid)))
|
||||
Buffers: shared hit=4
|
||||
Planning:
|
||||
Buffers: shared hit=42
|
||||
Planning Time: 0.276 ms
|
||||
Execution Time: 0.035 ms
|
||||
Planning Time: 0.286 ms
|
||||
Execution Time: 0.039 ms
|
||||
(9 rows)
|
||||
|
||||
BEGIN
|
||||
@@ -38,37 +38,37 @@ DROP INDEX
|
||||
=== 3. WITHOUT index: first page ===
|
||||
QUERY PLAN
|
||||
--------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=2487.71..2487.84 rows=51 width=78) (actual time=4.235..4.239 rows=51 loops=1)
|
||||
Buffers: shared hit=946
|
||||
-> Sort (cost=2487.71..2538.02 rows=20122 width=78) (actual time=4.234..4.236 rows=51 loops=1)
|
||||
Limit (cost=2472.45..2472.58 rows=51 width=78) (actual time=4.141..4.146 rows=51 loops=1)
|
||||
Buffers: shared hit=940
|
||||
-> Sort (cost=2472.45..2522.16 rows=19884 width=78) (actual time=4.141..4.143 rows=51 loops=1)
|
||||
Sort Key: created_at, id
|
||||
Sort Method: top-N heapsort Memory: 31kB
|
||||
Buffers: shared hit=946
|
||||
-> Seq Scan on messages (cost=0.00..1816.40 rows=20122 width=78) (actual time=0.011..3.325 rows=20000 loops=1)
|
||||
Buffers: shared hit=940
|
||||
-> Seq Scan on messages (cost=0.00..1809.08 rows=19884 width=78) (actual time=0.004..3.157 rows=20000 loops=1)
|
||||
Filter: (chat_id = '00000000-0000-4000-8000-000000000100'::uuid)
|
||||
Rows Removed by Filter: 50112
|
||||
Buffers: shared hit=940
|
||||
Rows Removed by Filter: 50006
|
||||
Buffers: shared hit=934
|
||||
Planning:
|
||||
Buffers: shared hit=16
|
||||
Planning Time: 0.098 ms
|
||||
Execution Time: 4.249 ms
|
||||
Planning Time: 0.091 ms
|
||||
Execution Time: 4.167 ms
|
||||
(14 rows)
|
||||
|
||||
=== 4. WITHOUT index: deep page ===
|
||||
QUERY PLAN
|
||||
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=2215.87..2216.00 rows=51 width=78) (actual time=3.117..3.121 rows=51 loops=1)
|
||||
Buffers: shared hit=940
|
||||
-> Sort (cost=2215.87..2219.53 rows=1466 width=78) (actual time=3.116..3.118 rows=51 loops=1)
|
||||
Limit (cost=2206.05..2206.17 rows=51 width=78) (actual time=2.882..2.886 rows=51 loops=1)
|
||||
Buffers: shared hit=934
|
||||
-> Sort (cost=2206.05..2209.56 rows=1407 width=78) (actual time=2.881..2.883 rows=51 loops=1)
|
||||
Sort Key: created_at, id
|
||||
Sort Method: top-N heapsort Memory: 31kB
|
||||
Buffers: shared hit=940
|
||||
-> Seq Scan on messages (cost=0.00..2166.96 rows=1466 width=78) (actual time=0.605..2.853 rows=5000 loops=1)
|
||||
Buffers: shared hit=934
|
||||
-> Seq Scan on messages (cost=0.00..2159.11 rows=1407 width=78) (actual time=0.628..2.654 rows=5000 loops=1)
|
||||
Filter: ((chat_id = '00000000-0000-4000-8000-000000000100'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 04:10:00+00'::timestamp with time zone, '47ba2a9c-d238-4807-2008-6ea72cb0f95c'::uuid)))
|
||||
Rows Removed by Filter: 65112
|
||||
Buffers: shared hit=940
|
||||
Planning Time: 0.069 ms
|
||||
Execution Time: 3.133 ms
|
||||
Rows Removed by Filter: 65006
|
||||
Buffers: shared hit=934
|
||||
Planning Time: 0.059 ms
|
||||
Execution Time: 2.898 ms
|
||||
(12 rows)
|
||||
|
||||
ROLLBACK
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Fresh volume: migrations from scratch + public smoke
|
||||
# date: 2026-10-07T14:18:43Z
|
||||
$ APP_PORT=18090 docker compose -p lab2-clean up -d --wait
|
||||
# date: 2026-10-08T21:04:06Z
|
||||
$ docker compose -p lab2-clean up -d --wait
|
||||
Container lab2-clean-api-1 Created
|
||||
Container lab2-clean-api-1 Healthy
|
||||
Container lab2-clean-migrate-1 Created
|
||||
@@ -14,7 +14,7 @@ $ APP_PORT=18090 docker compose -p lab2-clean up -d --wait
|
||||
$ docker compose -p lab2-clean logs migrate
|
||||
INFO migrate: applying 0001_init
|
||||
INFO migrate: migrations up to date: 1 applied now, 0 before
|
||||
$ make test BASE_URL=http://localhost:18090
|
||||
$ make test
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
$ docker compose -p lab2-clean run --rm migrate # second run
|
||||
INFO migrate: migrations up to date: 0 applied now, 1 before
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# Persistence: API + PostgreSQL + Valkey restarted, volume kept, same token
|
||||
# date: 2026-10-07T14:19:03Z
|
||||
# date: 2026-10-08T21:04:36Z
|
||||
## containers BEFORE
|
||||
api 2026-10-07T14:18:25.262485419Z running restarts=0
|
||||
postgres 2026-10-07T14:18:22.306271835Z running restarts=0
|
||||
valkey 2026-10-07T14:18:21.888265501Z running restarts=0
|
||||
api 2026-10-08T21:04:21.524285049Z running restarts=0
|
||||
postgres 2026-10-08T21:04:18.312105839Z running restarts=0
|
||||
valkey 2026-10-08T21:04:18.312749256Z running restarts=0
|
||||
volume messenger-lab2_pgdata
|
||||
|
||||
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
@@ -11,9 +11,9 @@ Executing explicit persistence hook; hook output suppressed to avoid leaking sec
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
## containers AFTER (StartedAt changed for all three)
|
||||
api 2026-10-07T14:19:08.428103009Z running restarts=0
|
||||
postgres 2026-10-07T14:19:05.240867716Z running restarts=0
|
||||
valkey 2026-10-07T14:19:05.240850591Z running restarts=0
|
||||
api 2026-10-08T21:04:41.315237919Z running restarts=0
|
||||
postgres 2026-10-08T21:04:38.136785584Z running restarts=0
|
||||
valkey 2026-10-08T21:04:38.136211584Z running restarts=0
|
||||
volume messenger-lab2_pgdata
|
||||
|
||||
$ docker compose logs migrate | tail -1
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
# date: 2026-10-07T14:19:14Z
|
||||
# date: 2026-10-08T21:04:36Z
|
||||
$ make check
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
$ make test
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
# date: 2026-10-07T14:19:14Z
|
||||
# date: 2026-10-08T21:04:47Z
|
||||
$ make test-student
|
||||
BASE_URL="http://localhost:18080" sh student-tests/run_all.sh
|
||||
== own_tests.py
|
||||
ok - malformed JSON -> 400 invalid_request
|
||||
ok - foreign chat access -> 404 (no leak)
|
||||
@@ -27,18 +26,18 @@ PASS: 7 checks
|
||||
ok - 20 concurrent registrations of one username -> 1x201, 19x409, 1 row
|
||||
ok - chat with unknown member -> 400 and transaction rolled back (no orphan chat)
|
||||
ok - password stored as $argon2id$..., sessions keep only sha256(token)
|
||||
ok - migrations run twice more: schema_migrations and data unchanged (1:49)
|
||||
ok - migrations run twice more: schema_migrations and data unchanged (1:113)
|
||||
PASS: 4 checks
|
||||
|
||||
== dependency_test.py
|
||||
ok - Valkey caches sessions with TTL<=300s and keeps logout tombstones
|
||||
ok - Valkey stopped: ready=200, reads/writes OK, revoked token 401, 4 ms/request
|
||||
ok - Valkey stopped: ready=200, reads/writes OK, revoked token 401, 3 ms/request
|
||||
ok - PostgreSQL stopped: live=200, ready/business=503 in 0.0s total, unverified token not trusted
|
||||
ok - PostgreSQL started again: API recovers without restart, data intact
|
||||
PASS: 4 checks
|
||||
|
||||
== sigterm_test.sh
|
||||
api stopped in 0s, exit code 0 (0 = graceful, 137 = SIGKILL)
|
||||
api stopped in 1s, exit code 0 (0 = graceful, 137 = SIGKILL)
|
||||
PASS: graceful SIGTERM shutdown, api restarted
|
||||
|
||||
ALL STUDENT TESTS PASSED
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
-- Initial schema for lab2. Applied once by app/migrate.py inside one transaction.
|
||||
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL,
|
||||
@@ -18,7 +16,6 @@ CREATE TABLE chats (
|
||||
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
-- position keeps member_ids in the order the creator sent them.
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
@@ -26,7 +23,6 @@ CREATE TABLE chat_members (
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
-- "Chats of a user": GET /chats starts from the caller's memberships.
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
@@ -35,18 +31,13 @@ CREATE TABLE messages (
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
-- The sender must be a member of the chat, enforced by the database itself.
|
||||
CONSTRAINT messages_sender_member_fk FOREIGN KEY (chat_id, sender_id)
|
||||
REFERENCES chat_members (chat_id, user_id),
|
||||
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
|
||||
);
|
||||
|
||||
-- Keyset pagination of history: WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
-- ORDER BY created_at, id LIMIT n. Justified by EXPLAIN in evidence/explain_history.txt.
|
||||
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
|
||||
|
||||
-- Sessions: PostgreSQL is the source of truth; Valkey only caches lookups.
|
||||
-- token_hash = sha256(token); the raw token is never stored.
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/bin/sh
|
||||
# Generate local synthetic credentials into ./secrets (git-ignored). Idempotent:
|
||||
# existing files are kept, so a running stack keeps working. Prints no secret values.
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
@@ -18,7 +16,6 @@ printf 'postgresql://messenger:%s@postgres:5432/messenger\n' "$PG_PASS" > secret
|
||||
if [ ! -f secrets/valkey.conf ]; then
|
||||
{
|
||||
printf 'requirepass %s\n' "$(gen)"
|
||||
# Pure cache: PostgreSQL holds the sessions, so no RDB/AOF is needed.
|
||||
printf 'save ""\nappendonly no\n'
|
||||
printf 'maxmemory 64mb\nmaxmemory-policy volatile-lru\n'
|
||||
} > secrets/valkey.conf
|
||||
@@ -27,6 +24,5 @@ fi
|
||||
VK_PASS=$(sed -n 's/^requirepass //p' secrets/valkey.conf)
|
||||
printf 'redis://:%s@valkey:6379/0\n' "$VK_PASS" > secrets/cache_url
|
||||
|
||||
# Containers run as non-root users that do not own these files on Linux.
|
||||
chmod 644 secrets/*
|
||||
echo "secrets ready in ./secrets (not tracked by git)"
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
#!/bin/sh
|
||||
# Restart the API and ALL state stores (PostgreSQL, Valkey), keeping volumes.
|
||||
# Never `down -v`, never flush, never re-seed. Migrations run again (idempotent).
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
docker compose stop api
|
||||
docker compose stop valkey postgres
|
||||
# depends_on brings postgres, valkey and migrate up first; --wait = api healthcheck (/health/ready).
|
||||
docker compose up -d --no-build --wait api
|
||||
docker compose ps --all --format 'table {{.Service}}\t{{.Status}}'
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sessions: wrong password, Basic/Bearer separation, X-User-Id ignored, logout, expiry.
|
||||
|
||||
Expiry runs against the api-short-ttl service (SESSION_TTL_SECONDS=2):
|
||||
docker compose --profile ttl-test up -d --wait api-short-ttl
|
||||
"""
|
||||
import base64
|
||||
import time
|
||||
import uuid
|
||||
@@ -20,7 +15,6 @@ def main():
|
||||
alice = c.user("auth")
|
||||
reg = alice["registration"]
|
||||
|
||||
# Wrong password and unknown user: the same 401 with a Basic challenge.
|
||||
r1 = c.call("POST", "/api/v1/auth/sessions", 401, headers=basic(reg["username"], "wrong-password-123"))
|
||||
r2 = c.call("POST", "/api/v1/auth/sessions", 401, headers=basic("nobody_" + uuid.uuid4().hex[:8], "wrong-password-123"))
|
||||
check(r1["json"]["error"]["message"] == r2["json"]["error"]["message"], "unknown user must look like a wrong password")
|
||||
@@ -31,7 +25,6 @@ def main():
|
||||
c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Bearer " + alice["token"]})
|
||||
ok("missing / malformed / non-Basic login -> 401")
|
||||
|
||||
# A password with ':' and non-ASCII characters survives Basic encoding.
|
||||
tricky = "пароль:с:двоеточием-" + uuid.uuid4().hex[:6]
|
||||
user = c.call("POST", "/api/v1/users", 201, body={"username": "u_colon_" + uuid.uuid4().hex[:8], "display_name": "Двоеточие", "password": tricky}, schema="User")["json"]
|
||||
c.call("POST", "/api/v1/auth/sessions", 201, headers=basic(user["username"], tricky), schema="Session")
|
||||
@@ -56,7 +49,6 @@ def main():
|
||||
c.call("GET", "/api/v1/users/me", 200, actor=second, schema="User")
|
||||
ok("logout revokes only the current token; repeat logout -> 401")
|
||||
|
||||
# Expiry: separate instance of the same image with SESSION_TTL_SECONDS=2.
|
||||
s = Client(SHORT_TTL_URL)
|
||||
bob = s.user("ttl")
|
||||
s.call("GET", "/api/v1/users/me", 200, actor=bob, schema="User")
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level-4 race-protection evidence: 10 clients send 100 messages concurrently;
|
||||
expect exactly 100 unique messages, with no loss/duplication under pagination.
|
||||
"""
|
||||
import sys
|
||||
import urllib.parse
|
||||
import concurrent.futures
|
||||
@@ -9,7 +6,7 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def main():
|
||||
@@ -36,8 +33,6 @@ def main():
|
||||
check(len(ids) == n_messages, "expected %d responses" % n_messages)
|
||||
check(len(set(ids)) == n_messages, "expected %d unique message ids, got %d" % (n_messages, len(set(ids))))
|
||||
|
||||
# Walk the full history back through the API to confirm the store itself
|
||||
# (not just the HTTP responses) holds exactly n_messages distinct rows.
|
||||
seen = []
|
||||
cursor = None
|
||||
while True:
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
"""PostgreSQL integrity: registration race, rollback of chat creation, repeatable migrations,
|
||||
password storage. Needs the compose stack (reads tables via `docker compose exec postgres`)."""
|
||||
import concurrent.futures
|
||||
import uuid
|
||||
|
||||
@@ -10,7 +8,6 @@ from stack import BASE_URL, Client, check, compose, main_wrapper, ok, psql
|
||||
def main():
|
||||
c = Client(BASE_URL)
|
||||
|
||||
# 1. Registration race: 20 parallel requests for one username.
|
||||
username = "u_race_" + uuid.uuid4().hex[:10]
|
||||
body = {"username": username, "display_name": "Гонка", "password": "Race-password-123"}
|
||||
|
||||
@@ -24,7 +21,6 @@ def main():
|
||||
check(psql("SELECT count(*) FROM users WHERE username = '%s'" % username) == "1", "exactly one row expected")
|
||||
ok("20 concurrent registrations of one username -> 1x201, 19x409, 1 row")
|
||||
|
||||
# 2. Rollback: the chat row is inserted, then the member insert hits the FK.
|
||||
alice = c.user("rb")
|
||||
title = "rollback-" + uuid.uuid4().hex
|
||||
c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]})
|
||||
@@ -33,14 +29,12 @@ def main():
|
||||
"chat without members exists")
|
||||
ok("chat with unknown member -> 400 and transaction rolled back (no orphan chat)")
|
||||
|
||||
# 3. Passwords are stored as Argon2id hashes, never plaintext.
|
||||
stored = psql("SELECT password_hash FROM users WHERE username = '%s'" % username)
|
||||
check(stored.startswith("$argon2id$") and "Race-password-123" not in stored, "password must be an Argon2id hash")
|
||||
check(psql("SELECT count(*) FROM information_schema.columns WHERE table_name = 'sessions' AND column_name = 'token'") == "0",
|
||||
"raw tokens must not be stored")
|
||||
ok("password stored as $argon2id$..., sessions keep only sha256(token)")
|
||||
|
||||
# 4. Migrations re-run without duplicates or data changes.
|
||||
before = psql("SELECT (SELECT count(*) FROM schema_migrations) || ':' || (SELECT count(*) FROM users)")
|
||||
compose("run", "--rm", "--no-deps", "migrate")
|
||||
compose("run", "--rm", "--no-deps", "migrate")
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Valkey's role and failures of each dependency. STOPS AND STARTS containers of this stack.
|
||||
|
||||
- Valkey really caches sessions and holds logout tombstones.
|
||||
- Valkey down: API keeps working (cache bypassed), readiness stays 200.
|
||||
- PostgreSQL down: bounded 503 quickly, readiness 503, liveness 200; an unverifiable
|
||||
token is never accepted; no token is still 401. Recovery after start.
|
||||
"""
|
||||
import time
|
||||
|
||||
from stack import BASE_URL, Client, Failure, check, compose, main_wrapper, ok, valkey
|
||||
@@ -27,7 +20,6 @@ def main():
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
history = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
|
||||
# Role of Valkey: a session lookup fills the cache, logout leaves a tombstone.
|
||||
before = int(valkey("DBSIZE"))
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
keys = valkey("--scan", "--pattern", "session:*").split()
|
||||
@@ -41,13 +33,12 @@ def main():
|
||||
check(tombstones, "logout must leave a 'revoked' tombstone in the cache")
|
||||
ok("Valkey caches sessions with TTL<=300s and keeps logout tombstones")
|
||||
|
||||
# Valkey down -> the API bypasses the cache, PostgreSQL stays the source of truth.
|
||||
try:
|
||||
compose("stop", "valkey")
|
||||
c.call("GET", "/health/ready", 200)
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
c.message(bob, chat, "без кэша")
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=temp) # revoked in PostgreSQL too
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=temp)
|
||||
start = time.monotonic()
|
||||
for _ in range(10):
|
||||
c.call("GET", history + "?limit=1", actor=alice, schema="MessagePage")
|
||||
@@ -57,8 +48,7 @@ def main():
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
|
||||
# PostgreSQL down -> bounded 503, never anonymous access.
|
||||
fresh = c.user("dbdown") # token never looked up yet: not in the cache
|
||||
fresh = c.user("dbdown")
|
||||
try:
|
||||
compose("stop", "postgres")
|
||||
c.call("GET", "/health/live", 200)
|
||||
@@ -67,8 +57,8 @@ def main():
|
||||
check(r["json"]["error"]["code"] == "unavailable", "readiness must report unavailable")
|
||||
c.call("GET", "/api/v1/chats", 503, actor=alice)
|
||||
c.call("POST", history, 503, actor=alice, body={"text": "в никуда"})
|
||||
c.call("GET", "/api/v1/users/me", 503, actor=fresh) # cannot verify -> not trusted
|
||||
c.call("GET", "/api/v1/users/me", 401) # no credentials at all
|
||||
c.call("GET", "/api/v1/users/me", 503, actor=fresh)
|
||||
c.call("GET", "/api/v1/users/me", 401)
|
||||
elapsed = time.monotonic() - start
|
||||
check(elapsed < 20, "errors must be bounded in time (%.1fs)" % elapsed)
|
||||
ok("PostgreSQL stopped: live=200, ready/business=503 in %.1fs total, unverified token not trusted" % elapsed)
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
#!/bin/sh
|
||||
# Seed synthetic history (20 000 messages in one chat + 50 000 in 50 other chats) and
|
||||
# record EXPLAIN (ANALYZE, BUFFERS) of the exact keyset queries used by the API,
|
||||
# with and without messages_chat_history_idx. Output: evidence/explain_history.txt
|
||||
# Seeding is idempotent (fixed IDs, ON CONFLICT DO NOTHING); data is synthetic.
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
@@ -15,7 +11,6 @@ INSERT INTO users (id, username, display_name, password_hash) VALUES
|
||||
('00000000-0000-4000-8000-000000000002', 'seed_explain_b', 'Seed B', 'not-a-login')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- chat ...0100 is the measured one; ...0101-0150 are background noise.
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
SELECT ('00000000-0000-4000-8000-' || lpad((100 + g)::text, 12, '0'))::uuid, 'explain ' || g, now()
|
||||
FROM generate_series(0, 50) g
|
||||
@@ -50,7 +45,6 @@ SQL
|
||||
$PSQL -tA -c "SELECT '# messages total: ' || count(*) || ', in measured chat: ' || count(*) FILTER (WHERE chat_id = '00000000-0000-4000-8000-000000000100') FROM messages"
|
||||
echo
|
||||
$PSQL <<'SQL'
|
||||
-- The same statements as app/storage.py (Store.list_messages), as prepared statements.
|
||||
PREPARE first_page(uuid, int) AS
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = $1 ORDER BY created_at, id LIMIT $2;
|
||||
@@ -65,7 +59,6 @@ EXPLAIN (ANALYZE, BUFFERS) EXECUTE first_page('00000000-0000-4000-8000-000000000
|
||||
EXPLAIN (ANALYZE, BUFFERS) EXECUTE next_page('00000000-0000-4000-8000-000000000100',
|
||||
timestamptz '2026-01-01' + interval '15000 seconds', md5('explain-0-15000')::uuid, 51);
|
||||
|
||||
-- Same queries without the index, inside a transaction that is rolled back.
|
||||
BEGIN;
|
||||
DROP INDEX messages_chat_history_idx;
|
||||
\echo '=== 3. WITHOUT index: first page ==='
|
||||
|
||||
@@ -1,13 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Student-written negative/edge-case tests, additional to the public tests/smoke.py.
|
||||
|
||||
Covers level-4 requirements from README.md:
|
||||
- malformed JSON
|
||||
- foreign chat access
|
||||
- empty message text
|
||||
- duplicate username
|
||||
- multi-page pagination traversal
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
@@ -17,7 +8,7 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
from client import Client, check
|
||||
|
||||
PASSED = 0
|
||||
|
||||
@@ -46,7 +37,6 @@ def main():
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"]
|
||||
|
||||
# 1. Malformed JSON body -> 400 invalid_request, not a 500.
|
||||
status, body = raw_call(
|
||||
base_url, "POST", "/api/v1/users",
|
||||
data=b'{"username": "broken", "display_name": ',
|
||||
@@ -57,24 +47,19 @@ def main():
|
||||
check(parsed["error"]["code"] == "invalid_request", "malformed JSON must report invalid_request")
|
||||
ok("malformed JSON -> 400 invalid_request")
|
||||
|
||||
# 2. Foreign chat: eve is not a member -> 404, not 403 (no existence leak).
|
||||
c.call("GET", path, 404, actor=eve)
|
||||
c.call("GET", path + "/messages", 404, actor=eve)
|
||||
ok("foreign chat access -> 404 (no leak)")
|
||||
|
||||
# 3. Empty / whitespace-only message text -> 400.
|
||||
c.call("POST", path + "/messages", 400, actor=alice, body={"text": ""})
|
||||
c.call("POST", path + "/messages", 400, actor=alice, body={"text": " "})
|
||||
ok("empty/whitespace message text -> 400")
|
||||
|
||||
# 4. Duplicate username -> 409 conflict, original user untouched.
|
||||
c.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
||||
me = c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["json"]
|
||||
check(me == alice["user"], "existing user must be unaffected by a rejected duplicate registration")
|
||||
ok("duplicate username -> 409, original user intact")
|
||||
|
||||
# 5. Multi-page pagination traversal: write N messages, walk every page with a small
|
||||
# limit and confirm the full, ordered, duplicate-free set is recovered.
|
||||
sent = [c.message(alice, chat, "page-msg-%d" % i)["json"] for i in range(7)]
|
||||
collected = []
|
||||
cursor = None
|
||||
@@ -96,8 +81,6 @@ def main():
|
||||
check(tail == sorted(tail, key=lambda m: (m["created_at"], m["id"])), "pagination must stay ordered")
|
||||
ok("multi-page pagination traversal: %d pages, %d messages, no dup/loss" % (pages, len(collected)))
|
||||
|
||||
# 6. A cursor is bound to the chat it was issued for: reusing it on a
|
||||
# different chat the same actor can also read must be rejected.
|
||||
first_page = c.call("GET", path + "/messages?limit=1", actor=alice, schema="MessagePage")["json"]
|
||||
check(first_page["next_cursor"], "need a non-null cursor to test cross-chat reuse")
|
||||
chat2 = c.call(
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
#!/bin/sh
|
||||
# All student tests in one command. Needs the running compose stack; starts the
|
||||
# short-TTL instance itself. dependency_test/sigterm_test STOP AND START containers.
|
||||
# Usage: BASE_URL=http://localhost:8080 student-tests/run_all.sh
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/bin/sh
|
||||
# Graceful shutdown of the compose api service: SIGTERM -> exit 0 within 10s
|
||||
# (not SIGKILL 137), then the service is started again. Volumes are untouched.
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Shared helpers for student tests: public client + direct access to the compose stack."""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -6,7 +5,7 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402,F401
|
||||
from client import Client, Failure, check
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
SHORT_TTL_URL = os.environ.get("SHORT_TTL_URL", "http://localhost:8081")
|
||||
@@ -20,7 +19,6 @@ def ok(label):
|
||||
|
||||
|
||||
def compose(*args, check_rc=True):
|
||||
"""docker compose in the repository root; output is captured, never printed raw."""
|
||||
proc = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True)
|
||||
if check_rc and proc.returncode != 0:
|
||||
raise Failure("docker compose %s failed: %s" % (args[0], proc.stderr.strip()[-300:]))
|
||||
@@ -28,12 +26,10 @@ def compose(*args, check_rc=True):
|
||||
|
||||
|
||||
def psql(sql):
|
||||
"""Run SQL inside the postgres container (local socket, no password on the wire)."""
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAX", "-c", sql).strip()
|
||||
|
||||
|
||||
def valkey(*args):
|
||||
"""valkey-cli with the password read inside the container, never on this host's argv."""
|
||||
cmd = 'valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/valkey_conf)" "$@"'
|
||||
return compose("exec", "-T", "valkey", "sh", "-c", cmd, "valkey-cli", *args).strip()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user