forked from mtusi2026/mtusi2026lab2
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6c1e93bb09 |
+4
-9
@@ -1,11 +1,6 @@
|
|||||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
# Local loopback port; internal API port is 8080.
|
||||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
APP_PORT=18082
|
||||||
APP_HOST=0.0.0.0
|
|
||||||
APP_PORT=8080
|
|
||||||
APP_ENV=lab
|
APP_ENV=lab
|
||||||
SESSION_TTL_SECONDS=3600
|
SESSION_TTL_SECONDS=3600
|
||||||
# Choose credentials locally. File paths contain no secret values.
|
# python scripts/bootstrap.py creates ignored secrets/ files.
|
||||||
DATABASE_URL_FILE=/run/secrets/database_url
|
# Compose supplies 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,2 @@
|
|||||||
|
*.sh text eol=lf
|
||||||
|
*.cmd text eol=crlf
|
||||||
@@ -1,18 +1,32 @@
|
|||||||
## Лабораторная 2
|
## Лабораторная 2
|
||||||
|
|
||||||
Автор / группа: TODO
|
Автор / группа: Щербаков Марк Игоревич / БПИ2303
|
||||||
Целевая оценка (3/4/5): TODO
|
Целевая оценка (3/4/5): 3
|
||||||
Трек 5, если заявлен: TODO
|
Трек 5, если заявлен: не заявлен
|
||||||
|
|
||||||
Что реализовано и что перенесено: TODO
|
Пользователи, чаты, членство, сообщения и сессии перенесены в PostgreSQL.
|
||||||
Команды запуска из чистого clone: TODO
|
HTTP-сервер и проверки входных данных взяты из собственной lab1. Регистрация
|
||||||
Результаты проверок и ссылка на REPORT.md: TODO
|
теперь требует password с scrypt; Basic создаёт opaque Bearer-сессию с expiry,
|
||||||
Ограничения / известные ошибки: TODO
|
logout отзывает текущий токен. Добавлены миграции и Compose с именованным volume.
|
||||||
Источники и использование ИИ: TODO
|
|
||||||
|
|
||||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
Запуск: `python scripts/bootstrap.py`, затем
|
||||||
- [ ] Контракт и публичные тесты не ослаблены.
|
`docker compose --env-file .env up -d --build --wait`.
|
||||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
Полная проверка: `python scripts/verify.py --output evidence/grade3-checks.txt`.
|
||||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
На Linux перед проверкой выполнить `chmod +x scripts/restart.sh`.
|
||||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
|
||||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
Публичные smoke/persistence, 10 собственных тестов, повтор миграций и короткий
|
||||||
|
TTL проверены на реальных контейнерах. Windows запускал Python-эквиваленты
|
||||||
|
целей Make; Linux job добавлен в CI, удалённый CI пока не запускался.
|
||||||
|
[Отчёт](../REPORT.md), [протокол](../evidence/grade3-checks.txt).
|
||||||
|
|
||||||
|
Ограничения: один API и одна БД на одном host; нет HA, backup/restore и Redis,
|
||||||
|
HTTP только localhost. Использование: синтетические учебные данные.
|
||||||
|
Источники перечислены в REPORT.md. OpenAI Codex использован при реализации,
|
||||||
|
проверках и подготовке документации.
|
||||||
|
|
||||||
|
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||||
|
- [x] Контракт и публичные тесты не ослаблены.
|
||||||
|
- [x] Команды check и test выполнены через Python; приложен реальный вывод.
|
||||||
|
- [x] Полный restart API/БД и сохранность действующей сессии воспроизведены.
|
||||||
|
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||||
|
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
name: Application
|
||||||
|
on: [push, pull_request]
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
jobs:
|
||||||
|
application:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.12'
|
||||||
|
- run: python scripts/bootstrap.py
|
||||||
|
- run: docker compose --env-file .env up -d --build --wait
|
||||||
|
- run: make check test PYTHON=python BASE_URL=http://localhost:18082
|
||||||
|
- run: python -m unittest discover -s student-tests -v
|
||||||
|
env:
|
||||||
|
BASE_URL: http://localhost:18082
|
||||||
|
NO_PROXY: localhost,127.0.0.1
|
||||||
|
- run: chmod +x scripts/restart.sh && make test-persistence PYTHON=python BASE_URL=http://localhost:18082 ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
- if: always()
|
||||||
|
run: docker compose down
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
FROM python:3.12.12-slim-bookworm
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 APP_HOST=0.0.0.0 APP_PORT=8080
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt ./
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt \
|
||||||
|
&& groupadd --gid 10001 messenger \
|
||||||
|
&& useradd --uid 10001 --gid messenger --no-create-home --shell /usr/sbin/nologin messenger
|
||||||
|
COPY --chown=10001:10001 src/ ./src/
|
||||||
|
COPY --chown=10001:10001 migrations/ ./migrations/
|
||||||
|
USER 10001:10001
|
||||||
|
EXPOSE 8080
|
||||||
|
STOPSIGNAL SIGTERM
|
||||||
|
HEALTHCHECK --interval=5s --timeout=5s --start-period=10s --retries=5 CMD ["python", "-m", "src.healthcheck"]
|
||||||
|
CMD ["python", "-m", "src.server"]
|
||||||
@@ -1,37 +1,246 @@
|
|||||||
# Отчёт — лабораторная 2
|
# Отчёт — лабораторная 2
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Щербаков Марк Игоревич, БПИ2303 (из отчёта lab1).
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка: **«3»**. Уровни 4/5 не заявляются.
|
||||||
- Commit/PR: TODO после публикации
|
- Публикация commit/PR выполняется отдельно владельцем репозитория.
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Python 3.12.12, psycopg/psycopg-binary 3.2.6, psycopg-pool 3.2.6,
|
||||||
|
typing_extensions 4.16.0. HTTP-транспорт, валидация и cursor перенесены из
|
||||||
|
собственной `mtusi2026lab1-fork`; её файлы не изменены.
|
||||||
|
- OpenAI Codex использован для изучения задания, реализации, проверок и отчёта.
|
||||||
|
Обязательные `contracts/`, публичные `tests/` и README задания сохранены.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Нужны Docker с Linux-контейнерами и Compose v2, Python 3.12+ для локальных
|
||||||
|
проверок. Make необязателен: ниже приведены те же команды Python для Windows.
|
||||||
|
Все команды выполняются из корня этой лабораторной. Образы закреплены:
|
||||||
|
`python:3.12.12-slim-bookworm`, `postgres:16.10-bookworm`.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python scripts/bootstrap.py
|
||||||
|
docker compose --env-file .env config --quiet
|
||||||
|
docker compose --env-file .env up -d --build --wait
|
||||||
|
```
|
||||||
|
|
||||||
|
Bootstrap создаёт случайный пароль БД, два файла в игнорируемой `secrets/`
|
||||||
|
и локальный `.env`; существующие файлы не перезаписываются. Credentials
|
||||||
|
передаются Compose secrets, не включаются в образ. При повторном запуске с
|
||||||
|
существующим volume сохраните прежние secrets: изменение файла не изменяет
|
||||||
|
пароль уже созданной роли PostgreSQL.
|
||||||
|
|
||||||
|
API доступен на `http://127.0.0.1:18082`; readiness:
|
||||||
|
`http://127.0.0.1:18082/health/ready`. Порт задан в `.env` как `APP_PORT` и
|
||||||
|
публикуется только на loopback; внутри API слушает `0.0.0.0:8080`.
|
||||||
|
PostgreSQL доступен только внутри сети Compose. Если 18082 занят, измените
|
||||||
|
его в `.env` и передавайте соответствующий `BASE_URL` проверкам.
|
||||||
|
|
||||||
|
Миграции автоматически выполняются перед запуском HTTP-сервера. Ручное
|
||||||
|
безопасное повторение:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose exec -T api python -m src.database
|
||||||
|
```
|
||||||
|
|
||||||
|
Linux/macOS с Make:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
chmod +x scripts/restart.sh
|
||||||
|
make check PYTHON=python3
|
||||||
|
make test PYTHON=python3 BASE_URL=http://127.0.0.1:18082
|
||||||
|
make test-persistence PYTHON=python3 BASE_URL=http://127.0.0.1:18082 ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Windows PowerShell (эквиваленты целей Make, без установки Make):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:NO_PROXY='localhost,127.0.0.1'
|
||||||
|
$env:no_proxy='localhost,127.0.0.1'
|
||||||
|
python scripts/check_contract.py
|
||||||
|
python tests/smoke.py --base-url http://127.0.0.1:18082
|
||||||
|
python tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://127.0.0.1:18082
|
||||||
|
$env:BASE_URL='http://127.0.0.1:18082'
|
||||||
|
python -m unittest discover -s student-tests -v
|
||||||
|
```
|
||||||
|
|
||||||
|
`restart.sh` и Windows-аналог `restart.cmd` выполняют одну и ту же команду:
|
||||||
|
`docker compose --env-file .env restart postgres api`. Скрипты не удаляют volumes.
|
||||||
|
В CI Linux executable bit устанавливается явно перед вызовом публичной цели Make.
|
||||||
|
|
||||||
|
Полная автоматическая проверка из Windows или Linux с доступом к Docker:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# На Linux предварительно chmod +x scripts/restart.sh.
|
||||||
|
python scripts/verify.py --output evidence/grade3-checks.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
Этот сценарий дополнительно запускает временный API на свободном порту 18083
|
||||||
|
с TTL=2 и той же БД, удаляя только временный контейнер после проверки.
|
||||||
|
Основной API остаётся с TTL=3600. Основной порт можно переопределить
|
||||||
|
`--base-url http://127.0.0.1:ДРУГОЙ_ПОРТ`.
|
||||||
|
|
||||||
|
Факультативная полная проверка OpenAPI, отдельно от runtime:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m venv .venv
|
||||||
|
.\.venv\Scripts\python.exe -m pip install -r requirements-dev.txt
|
||||||
|
.\.venv\Scripts\python.exe scripts/validate_openapi.py
|
||||||
|
```
|
||||||
|
|
||||||
|
В Linux используйте `.venv/bin/python`. В CI добавлен отдельный
|
||||||
|
`.github/workflows/application.yml`: сборка → readiness → smoke → собственные
|
||||||
|
тесты → публичный persistence с настоящим `restart.sh`.
|
||||||
|
|
||||||
|
Безопасная остановка: `docker compose down` (данные остаются в именованном
|
||||||
|
volume). Повторный запуск: `docker compose --env-file .env up -d --wait`.
|
||||||
|
**Только для намеренного полного удаления учебных данных:** `docker compose down -v`.
|
||||||
|
Эта команда не используется ни в проверках, ни в restart hook.
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
C[HTTP-клиенты на localhost] --> A[API Python / потоки HTTP]
|
||||||
|
A --> P[Ограниченный pool psycopg]
|
||||||
|
P --> D[(PostgreSQL)]
|
||||||
|
D --> V[Именованный postgres_data volume]
|
||||||
|
```
|
||||||
|
|
||||||
|
API хранит в памяти только соединения, ключ cursor и состояние остановки.
|
||||||
|
Пользователи, чаты, членство, сообщения, сессии и ключ подписи cursor живут
|
||||||
|
в PostgreSQL. Redis/Valkey не используются: для «3» они необязательны.
|
||||||
|
Схема и транзакционные границы описаны в [infra/schema.md](infra/schema.md),
|
||||||
|
версионируемая миграция — [001_initial.sql](migrations/001_initial.sql).
|
||||||
|
|
||||||
|
Таблицы имеют UUID PK, FK, уникальный username, составной ключ членства,
|
||||||
|
проверки длины. Составной FK сообщения требует членства отправителя в чате.
|
||||||
|
Индекс `(chat_id, created_at, id)` обслуживает keyset-историю; индекс членства
|
||||||
|
начинается с `user_id`. Существование и доступ к чату проверяются до его
|
||||||
|
чтения/записи. Постороннему возвращается 404, без сессии — 401.
|
||||||
|
|
||||||
|
Создание чата и всех участников выполняется одной транзакцией. Проверка
|
||||||
|
неизвестного участника намеренно следует после INSERT чата: собственный тест
|
||||||
|
и SQL-проверка отсутствия чатов без участников подтверждают rollback.
|
||||||
|
Регистрация опирается на UNIQUE БД; конкурентные INSERT дают одну 201 и остальные
|
||||||
|
409. Ответ 201/204 формируется только после выхода из транзакции с COMMIT.
|
||||||
|
Запросы параметризованы. Pool: 1–8 соединений, очередь до 32, ожидание 2 с,
|
||||||
|
connect timeout 3 с, statement timeout 3 с, lock timeout 2 с.
|
||||||
|
|
||||||
|
История сортируется по `(created_at, id)`. Подписанный HMAC-SHA256 cursor связан
|
||||||
|
с чатом либо владельцем списка чатов; ключ хранится в БД и переживает рестарт.
|
||||||
|
`limit+1` определяет наличие следующей страницы без подсчёта всей истории.
|
||||||
|
Отправки в одном чате сериализованы блокировкой строки чата; время следующей
|
||||||
|
записи — максимум времени БД и времени предыдущей + 1 мкс. Это сохраняет
|
||||||
|
порядок записей даже при откате часов внутри чата. Snapshot между HTTP-запросами
|
||||||
|
не предоставляется; после `next_cursor=null` новые записи читаются новым обходом.
|
||||||
|
Создание разных чатов использует часы БД без глобальной логической шкалы;
|
||||||
|
поздно завершившаяся конкурентная транзакция может потребовать нового обхода списка.
|
||||||
|
|
||||||
|
Миграции выполняются под transaction advisory lock. Файл и SHA-256 записываются
|
||||||
|
в `schema_migrations` атомарно с DDL; изменение уже применённого файла вызывает
|
||||||
|
ошибку. Новые изменения схемы добавляются новым номером миграции. Перезапуск
|
||||||
|
не делает seed и не обнуляет таблицы.
|
||||||
|
|
||||||
|
Регистрация принимает пароль 12–128 Unicode code points. Библиотечный
|
||||||
|
`hashlib.scrypt`: N=16384, r=8, p=1, результат 32 байта, индивидуальная случайная
|
||||||
|
соль 16 байт. UTF-8 не усекается; сравнение через `hmac.compare_digest`.
|
||||||
|
Basic принимается только на `POST /api/v1/auth/sessions`, без JSON body;
|
||||||
|
пароль с двоеточием поддерживается. Bearer — `secrets.token_urlsafe(32)` с
|
||||||
|
256 битами случайности. В БД хранится только SHA-256 токена, `user_id` и
|
||||||
|
`expires_at`; password hash и сессионные поля не попадают в User.
|
||||||
|
Идентичные 401 и WWW-Authenticate возвращаются для неправильных credentials.
|
||||||
|
|
||||||
|
Каждый защищённый запрос проверяет сессию и expiry по часам PostgreSQL.
|
||||||
|
Logout удаляет текущую сессию; другие сессии пользователя сохраняются.
|
||||||
|
`X-User-Id` игнорируется. Истёкшие записи физически не очищаются автоматически,
|
||||||
|
но никогда не дают доступ; при росте БД нужна периодическая очистка.
|
||||||
|
|
||||||
|
| Настройка | Реальное использование |
|
||||||
|
| --- | --- |
|
||||||
|
| `APP_PORT` в `.env` | Публикуемый порт localhost, по умолчанию 18082 |
|
||||||
|
| `APP_HOST`, `APP_PORT` внутри API | 0.0.0.0:8080, заданы Compose |
|
||||||
|
| `APP_ENV` | Метка окружения в стартовом логе |
|
||||||
|
| `SESSION_TTL_SECONDS` | Абсолютный срок сессии, по умолчанию 3600 |
|
||||||
|
| `DATABASE_URL_FILE` | API читает DSN из `/run/secrets/database_url` |
|
||||||
|
| `DATABASE_URL` | Альтернатива для прямого запуска без Compose |
|
||||||
|
| `POSTGRES_PASSWORD_FILE` | Bootstrap БД из `/run/secrets/postgres_password` |
|
||||||
|
|
||||||
|
| Роль | Service / версия | Readiness | Volume | Порты и credentials |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| HTTP API | api / Python 3.12.12 | `/health/ready`, запрос к PostgreSQL | Нет | loopback 18082 → 8080, Compose secret DSN |
|
||||||
|
| БД | postgres / 16.10-bookworm | pg_isready; API отдельно проверяет соединение/схему | postgres_data | Только внутренняя сеть, Compose secret password |
|
||||||
|
|
||||||
|
`/health/live` проверяет процесс, `/health/ready` — доступность PostgreSQL и схемы.
|
||||||
|
При ошибке соединения возвращается 503 общего формата; работа без действительной
|
||||||
|
сессии не разрешается. HTTP-тело ограничено 64 KiB. Унаследованы X-Request-Id,
|
||||||
|
Unicode-валидация, запрет лишних/дублирующихся JSON-полей и graceful shutdown.
|
||||||
|
Логи содержат метод, статус, request_id и длительность, без body и Authorization.
|
||||||
|
Контейнер API работает как UID 10001, с read-only FS, без capabilities.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Публичный smoke и минимум lab1 | `python tests/smoke.py --base-url http://127.0.0.1:18082` | PASS: пользователи, чаты, сообщения, пагинация, Unicode, доступ | [grade3-checks.txt](evidence/grade3-checks.txt) |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Схема и постоянное хранилище | Compose, SQL-проверки `scripts/verify.py` | PostgreSQL; все обязательные таблицы, PK/FK/UNIQUE | [schema.md](infra/schema.md), [миграция](migrations/001_initial.sql) |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Basic → Bearer, игнорирование X-User-Id | Публичный smoke, собственные auth tests | Basic только при входе; X-User-Id не даёт доступ и не меняет владельца | [grade3-checks.txt](evidence/grade3-checks.txt) |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| KDF, opaque token | SQL-проверки verify, Unicode password test | scrypt, 32 случайных байта токена, в БД только digest | [grade3-checks.txt](evidence/grade3-checks.txt) |
|
||||||
|
| Expiry | Отдельный API с `SESSION_TTL_SECONDS=2` | До срока 200, через 2,3 с — 401; logout истёкшего токена — 401 | [grade3-checks.txt](evidence/grade3-checks.txt) |
|
||||||
|
| Logout | Smoke и `test_logout_only_revokes_current_session` | Текущий токен отозван, другая сессия действует | [grade3-checks.txt](evidence/grade3-checks.txt) |
|
||||||
|
| Атомарное создание чата | Ошибки member_ids + SQL поиска orphan chats | 400; нет частичного чата/членства | [grade3-checks.txt](evidence/grade3-checks.txt) |
|
||||||
|
| Повторяемые миграции | Два запуска `python -m src.database`, сравнение семи счётчиков | PASS; счётчики таблиц не изменились | [grade3-checks.txt](evidence/grade3-checks.txt) |
|
||||||
|
| Сохранность данных и сессий | Публичный persistence + restart hook | Прежний токен читает то же сообщение после рестарта API и БД | [grade3-checks.txt](evidence/grade3-checks.txt) |
|
||||||
|
| Реальность hook, named volume | `docker inspect` до/после в verify | Оба StartedAt изменились, имя volume прежнее | [grade3-checks.txt](evidence/grade3-checks.txt) |
|
||||||
|
| Пагинация после рестарта | Дополнительный cursor-сценарий verify | Прежний cursor продолжает с правильной записи | [grade3-checks.txt](evidence/grade3-checks.txt) |
|
||||||
|
| Секреты вне Git | `.gitignore`, bootstrap, `.dockerignore` | `.env`, `secrets/`, `.venv/` игнорируются, volume вне репозитория | Конфигурация проекта |
|
||||||
|
| Полная схема контракта | `python scripts/validate_openapi.py` | PASS OpenAPI 3.1 / JSON Schema | [contracts.txt](evidence/contracts.txt) |
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
На Windows установлен Python 3.12.0, Make отсутствует: выполнены точные
|
||||||
|
Python-команды целей `check`, `test`, `test-persistence` с Windows hook.
|
||||||
|
Linux-команды Make и `restart.sh` включены в отдельный CI job; удалённый CI
|
||||||
|
в ходе этой работы не запускался.
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Проверки проведены 29 октября 2026 года, время протокола — UTC (Москва UTC+3).
|
||||||
|
Стенд: Windows, Docker Desktop 4.77.0 / Engine 29.5.3, Linux-контейнеры;
|
||||||
|
каждому сервису выделено не более 1 CPU и 256 MiB RAM. PostgreSQL 16.10,
|
||||||
|
Python API 3.12.12. Вывод smoke, собственных тестов, миграций и состояний
|
||||||
|
контейнеров сохранён в протоколе, без session tokens и credentials.
|
||||||
|
|
||||||
|
Цель эксперимента: проверить, что подтверждённая запись и действительная
|
||||||
|
сессия не зависят от памяти API. Публичный persistence создаёт синтетических
|
||||||
|
пользователей, чат и сообщение, держит токен только в памяти теста, вызывает
|
||||||
|
hook, ждёт readiness и сравнивает историю без повторного входа.
|
||||||
|
Дополнительный сценарий сохраняет cursor до того же рестарта и продолжает
|
||||||
|
чтение после него. Реальный `StartedAt` проверяется для обоих контейнеров.
|
||||||
|
PostgreSQL использует стандартные `fsync=on`, `synchronous_commit=on`,
|
||||||
|
`full_page_writes=on`; COMMIT подтверждает локальный WAL, не репликацию или backup.
|
||||||
|
|
||||||
|
Нагрузочное исследование, максимальный RPS, p50/p95/p99 и пиковые CPU/RAM
|
||||||
|
не измерялись и на «3» не заявляются. Собственный конкурентный сценарий
|
||||||
|
проверяет корректность 40 сообщений от 8 потоков, а не предельную производительность.
|
||||||
|
Перед проверками ожидается readiness; специального прогрева нет.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| Перезапуск API и PostgreSQL без удаления volumes | Данные и действующие сессии сохранены | Публичный persistence PASS, StartedAt обоих сервисов изменился | Готовность в бюджете публичного теста 90 с, потери подтверждённых сообщений нет |
|
||||||
|
| Повтор миграций | Нет seed/дубликатов | Все семь счётчиков совпали | Данные не изменились |
|
||||||
|
| Короткий TTL | После expiry доступ запрещён | 401 через 2,3 с | Повторный вход создаёт новую сессию |
|
||||||
|
| Неизвестный участник чата | Полный rollback | Нет orphan chats | Исправить member_ids и повторить |
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
Один API и один PostgreSQL на одном Docker-host. Подтверждена сохранность
|
||||||
|
при штатном полном рестарте с сохранённым volume; потеря host/volume, повреждение
|
||||||
|
диска и восстановление из backup не исследовались. HA, Redis, треки 4/5,
|
||||||
|
TLS и защита от brute force не входят в заявленный результат. HTTP опубликован
|
||||||
|
только на localhost и предназначен для синтетических учебных данных.
|
||||||
|
Неограниченный рост записей/истёкших сессий требует политики очистки.
|
||||||
|
`http.server` и поток на запрос сохранены из lab1; это учебный сервер.
|
||||||
|
|
||||||
|
Первичные источники: [контракт](contracts/README.md),
|
||||||
|
[scrypt в Python](https://docs.python.org/3.12/library/hashlib.html#hashlib.scrypt),
|
||||||
|
[secrets](https://docs.python.org/3.12/library/secrets.html),
|
||||||
|
[psycopg pool и COMMIT/rollback](https://www.psycopg.org/psycopg3/docs/advanced/pool.html),
|
||||||
|
[PostgreSQL transactions](https://www.postgresql.org/docs/16/tutorial-transactions.html),
|
||||||
|
[Basic RFC 7617](https://www.rfc-editor.org/rfc/rfc7617).
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
name: mtusi2026lab2
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16.10-bookworm
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: messenger
|
||||||
|
POSTGRES_DB: messenger
|
||||||
|
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||||
|
secrets:
|
||||||
|
- postgres_password
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD-SHELL, "pg_isready -U messenger -d messenger"]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 30
|
||||||
|
restart: unless-stopped
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 256m
|
||||||
|
api:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
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
|
||||||
|
secrets:
|
||||||
|
- database_url
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${APP_PORT:-18082}:8080"
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
read_only: true
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: [no-new-privileges:true]
|
||||||
|
stop_grace_period: 10s
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 256m
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
secrets:
|
||||||
|
postgres_password:
|
||||||
|
file: ./secrets/postgres_password
|
||||||
|
database_url:
|
||||||
|
file: ./secrets/database_url
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
UTC 2026-10-29T15:23:08.830114+00:00
|
||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
|
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
test_access_before_payload_validation (test_api.API.test_access_before_payload_validation) ... ok
|
||||||
|
test_bad_credentials_and_schemes (test_api.API.test_bad_credentials_and_schemes) ... ok
|
||||||
|
test_chat_atomic_invalid_members (test_api.API.test_chat_atomic_invalid_members) ... ok
|
||||||
|
test_concurrent_messages_and_keyset (test_api.API.test_concurrent_messages_and_keyset) ... ok
|
||||||
|
test_cursor_scope_and_tampering (test_api.API.test_cursor_scope_and_tampering) ... ok
|
||||||
|
test_json_and_sender_validation (test_api.API.test_json_and_sender_validation) ... ok
|
||||||
|
test_logout_only_revokes_current_session (test_api.API.test_logout_only_revokes_current_session) ... ok
|
||||||
|
test_registration_validation (test_api.API.test_registration_validation) ... ok
|
||||||
|
test_unicode_password_with_colon_and_max_length (test_api.API.test_unicode_password_with_colon_and_max_length) ... ok
|
||||||
|
test_username_race (test_api.API.test_username_race) ... ok
|
||||||
|
|
||||||
|
----------------------------------------------------------------------
|
||||||
|
Ran 10 tests in 11.305s
|
||||||
|
|
||||||
|
OK
|
||||||
|
PASS: no orphan chats after invalid compound operations
|
||||||
|
PASS: migrations applied
|
||||||
|
PASS: migrations applied
|
||||||
|
PASS: migrations repeated twice; all table counts unchanged: 77|26|50|93|73|1|1
|
||||||
|
PASS: password KDF and token digests stored, no plaintext fields
|
||||||
|
BEFORE_RESTART {"api": {"id": "b179e372934a", "started_at": "2026-10-29T15:20:00.638038777Z", "health": "healthy", "volumes": [], "memory_limit": 268435456, "nano_cpus": 1000000000}, "postgres": {"id": "f6c5ff81b339", "started_at": "2026-10-29T15:17:32.859839875Z", "health": "healthy", "volumes": ["mtusi2026lab2_postgres_data"], "memory_limit": 268435456, "nano_cpus": 1000000000}}
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
AFTER_RESTART {"api": {"id": "b179e372934a", "started_at": "2026-10-29T15:23:33.018502138Z", "health": "starting", "volumes": [], "memory_limit": 268435456, "nano_cpus": 1000000000}, "postgres": {"id": "f6c5ff81b339", "started_at": "2026-10-29T15:23:32.703945586Z", "health": "healthy", "volumes": ["mtusi2026lab2_postgres_data"], "memory_limit": 268435456, "nano_cpus": 1000000000}}
|
||||||
|
PASS: both containers restarted; named volume, session, users and signed cursor preserved
|
||||||
|
PASS: SESSION_TTL_SECONDS=2; valid then expired token rejected
|
||||||
|
PASS: grade-3 verification complete
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Схема и транзакции (проект до реализации запросов)
|
||||||
|
|
||||||
|
PostgreSQL — единственный источник истины. `users`: UUID PK, уникальный
|
||||||
|
username, display_name, hash scrypt с индивидуальной солью, UTC created_at.
|
||||||
|
`chats`: UUID PK, title, created_at. `memberships`: составной PK
|
||||||
|
(chat_id, user_id), FK на чаты и пользователей, ordinal для порядка участников.
|
||||||
|
`messages`: UUID PK, FK chat_id, составной FK (chat_id, sender_id) на членство,
|
||||||
|
text, created_at; B-tree (chat_id, created_at, id) для keyset-пагинации.
|
||||||
|
`sessions`: SHA-256 случайного токена как PK, FK user_id, expires_at; индекс
|
||||||
|
expiry. Сам bearer не сохраняется. `settings`: постоянный ключ подписи cursor.
|
||||||
|
`schema_migrations`: версия и checksum применённого файла.
|
||||||
|
|
||||||
|
Регистрация: уникальность обеспечивает БД, конфликт INSERT превращается в 409.
|
||||||
|
Создание чата: INSERT чата, проверка пользователей и INSERT всех участников в
|
||||||
|
одной транзакции; любая ошибка откатывает и чат, и участников.
|
||||||
|
Отправка: блокировка строки чата FOR UPDATE, проверка членства, назначение
|
||||||
|
времени после последнего сообщения, INSERT и COMMIT до ответа 201.
|
||||||
|
Чтение: доступ и страница в одной транзакции; участники неизменяемы.
|
||||||
|
Вход: KDF вне транзакции, затем INSERT сессии и COMMIT.
|
||||||
|
Logout: DELETE сессии и COMMIT до 204. Expiry проверяется по часам PostgreSQL
|
||||||
|
на каждом запросе и не продлевается при рестарте.
|
||||||
|
Миграции: advisory transaction lock, DDL и запись версии одним COMMIT;
|
||||||
|
повторный запуск не создаёт данные повторно; изменение применённой миграции — ошибка.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
CREATE TABLE users (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||||
|
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||||
|
password_hash text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
CREATE TABLE chats (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
CREATE TABLE memberships (
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id),
|
||||||
|
ordinal integer NOT NULL CHECK (ordinal >= 0),
|
||||||
|
PRIMARY KEY (chat_id, user_id),
|
||||||
|
UNIQUE (chat_id, ordinal)
|
||||||
|
);
|
||||||
|
CREATE INDEX memberships_user ON memberships (user_id, chat_id);
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||||
|
sender_id uuid NOT NULL,
|
||||||
|
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||||
|
created_at timestamptz NOT NULL,
|
||||||
|
FOREIGN KEY (chat_id, sender_id) REFERENCES memberships(chat_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX messages_history ON messages (chat_id, created_at, id);
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
token_hash text PRIMARY KEY,
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id),
|
||||||
|
expires_at timestamptz NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX sessions_expiry ON sessions (expires_at);
|
||||||
|
CREATE TABLE settings (key text PRIMARY KEY, value text NOT NULL);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
psycopg[binary]==3.2.6
|
||||||
|
psycopg-pool==3.2.6
|
||||||
|
typing_extensions==4.16.0
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"""Generate local synthetic credentials without printing or overwriting them."""
|
||||||
|
from pathlib import Path
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
root = Path(__file__).resolve().parents[1]
|
||||||
|
directory = root / "secrets"
|
||||||
|
directory.mkdir(exist_ok=True)
|
||||||
|
password_file = directory / "postgres_password"
|
||||||
|
if not password_file.exists():
|
||||||
|
password_file.write_text(secrets.token_hex(32), encoding="ascii")
|
||||||
|
url = directory / "database_url"
|
||||||
|
if not url.exists():
|
||||||
|
password = password_file.read_text(encoding="ascii").strip()
|
||||||
|
url.write_text(f"postgresql://messenger:{password}@postgres:5432/messenger", encoding="ascii")
|
||||||
|
env = root / ".env"
|
||||||
|
if not env.exists():
|
||||||
|
env.write_bytes((root / ".env.example").read_bytes())
|
||||||
|
print("Local .env and secrets ready; existing files preserved.")
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0.."
|
||||||
|
docker compose --env-file .env restart postgres api
|
||||||
Executable
+4
@@ -0,0 +1,4 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
docker compose --env-file .env restart postgres api
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""Reproducible grade-3 checks against this Compose project (synthetic data)."""
|
||||||
|
import argparse
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / "tests"))
|
||||||
|
from client import Client, Failure
|
||||||
|
|
||||||
|
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||||
|
|
||||||
|
|
||||||
|
def command(args, capture=False):
|
||||||
|
result = subprocess.run(args, cwd=ROOT, text=True, encoding="utf-8", errors="replace",
|
||||||
|
stdout=subprocess.PIPE if capture else sys.stdout,
|
||||||
|
stderr=subprocess.STDOUT, timeout=180)
|
||||||
|
if result.returncode:
|
||||||
|
# Do not dump Docker config, environment or request credentials.
|
||||||
|
raise RuntimeError("Command failed: " + args[0])
|
||||||
|
return result.stdout
|
||||||
|
|
||||||
|
|
||||||
|
def sql(query):
|
||||||
|
return command(COMPOSE + ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-Atc", query], True).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def wait_ready(url):
|
||||||
|
c = Client(url, timeout=5)
|
||||||
|
deadline = time.monotonic() + 90
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
c.call("GET", "/health/ready", schema="Health")
|
||||||
|
return c
|
||||||
|
except Failure:
|
||||||
|
time.sleep(0.5)
|
||||||
|
raise RuntimeError("Readiness deadline exceeded")
|
||||||
|
|
||||||
|
|
||||||
|
def container_state():
|
||||||
|
result = {}
|
||||||
|
for service in ("api", "postgres"):
|
||||||
|
cid = command(COMPOSE + ["ps", "-q", service], True).strip()
|
||||||
|
data = json.loads(command(["docker", "inspect", cid], True))[0]
|
||||||
|
result[service] = {"id": cid[:12], "started_at": data["State"]["StartedAt"],
|
||||||
|
"health": data["State"].get("Health", {}).get("Status"),
|
||||||
|
"volumes": [m["Name"] for m in data["Mounts"] if m["Type"] == "volume"],
|
||||||
|
"memory_limit": data["HostConfig"]["Memory"],
|
||||||
|
"nano_cpus": data["HostConfig"]["NanoCpus"]}
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--base-url", default="http://127.0.0.1:18082")
|
||||||
|
parser.add_argument("--output", help="UTF-8 evidence log, without credentials")
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.output:
|
||||||
|
sys.stdout = open(ROOT / args.output, "w", encoding="utf-8", buffering=1)
|
||||||
|
sys.stderr = sys.stdout
|
||||||
|
os.environ["NO_PROXY"] = "localhost,127.0.0.1"
|
||||||
|
os.environ["no_proxy"] = "localhost,127.0.0.1"
|
||||||
|
os.environ["BASE_URL"] = args.base_url
|
||||||
|
print("UTC", datetime.now(timezone.utc).isoformat(), flush=True)
|
||||||
|
c = wait_ready(args.base_url)
|
||||||
|
command([sys.executable, "scripts/check_contract.py"])
|
||||||
|
command([sys.executable, "tests/smoke.py", "--base-url", args.base_url])
|
||||||
|
command([sys.executable, "-m", "unittest", "discover", "-s", "student-tests", "-v"])
|
||||||
|
# Compare all relevant counts; a rolled-back chat must not remain as an orphan.
|
||||||
|
assert sql("SELECT count(*) FROM chats c WHERE NOT EXISTS (SELECT 1 FROM memberships m WHERE m.chat_id=c.id)") == "0"
|
||||||
|
print("PASS: no orphan chats after invalid compound operations", flush=True)
|
||||||
|
counts = "SELECT (SELECT count(*) FROM users),(SELECT count(*) FROM chats),(SELECT count(*) FROM memberships),(SELECT count(*) FROM messages),(SELECT count(*) FROM sessions),(SELECT count(*) FROM settings),(SELECT count(*) FROM schema_migrations)"
|
||||||
|
before = sql(counts)
|
||||||
|
command(COMPOSE + ["exec", "-T", "api", "python", "-m", "src.database"])
|
||||||
|
command(COMPOSE + ["exec", "-T", "api", "python", "-m", "src.database"])
|
||||||
|
assert sql(counts) == before
|
||||||
|
print("PASS: migrations repeated twice; all table counts unchanged: " + before, flush=True)
|
||||||
|
assert sql("SELECT bool_and(password_hash LIKE 'scrypt$16384$8$1$%') FROM users") == "t"
|
||||||
|
assert sql("SELECT bool_and(length(token_hash)=64) FROM sessions") == "t"
|
||||||
|
print("PASS: password KDF and token digests stored, no plaintext fields", flush=True)
|
||||||
|
|
||||||
|
alice, bob, _, chat = c.bootstrap()
|
||||||
|
first = c.message(alice, chat, "cursor before restart")["json"]
|
||||||
|
second = c.message(bob, chat, "cursor after restart")["json"]
|
||||||
|
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||||
|
page = c.call("GET", path + "?limit=1", actor=alice, schema="MessagePage")["json"]
|
||||||
|
from urllib.parse import quote
|
||||||
|
states = container_state()
|
||||||
|
print("BEFORE_RESTART " + json.dumps(states), flush=True)
|
||||||
|
hook = "scripts/restart.cmd" if os.name == "nt" else "scripts/restart.sh"
|
||||||
|
command([sys.executable, "tests/resilience.py", "--mode", "persistence", "--action-script", hook, "--base-url", args.base_url])
|
||||||
|
wait_ready(args.base_url)
|
||||||
|
after = container_state()
|
||||||
|
print("AFTER_RESTART " + json.dumps(after), flush=True)
|
||||||
|
for service in states:
|
||||||
|
assert states[service]["started_at"] != after[service]["started_at"]
|
||||||
|
assert states[service]["volumes"] == after[service]["volumes"]
|
||||||
|
resumed = c.call("GET", path + "?limit=1&cursor=" + quote(page["next_cursor"]), actor=alice, schema="MessagePage")["json"]
|
||||||
|
assert page["items"] == [first] and resumed["items"] == [second]
|
||||||
|
c.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
||||||
|
print("PASS: both containers restarted; named volume, session, users and signed cursor preserved", flush=True)
|
||||||
|
|
||||||
|
# Separate short-lived API, same persistent PostgreSQL; main API TTL is unchanged.
|
||||||
|
name = "mtusi2026lab2-expiry-check"
|
||||||
|
command(COMPOSE + ["run", "-d", "--no-deps", "--name", name, "-e", "SESSION_TTL_SECONDS=2", "-p", "127.0.0.1:18083:8080", "api"], True)
|
||||||
|
try:
|
||||||
|
short = wait_ready("http://127.0.0.1:18083")
|
||||||
|
actor = short.user("expiry")
|
||||||
|
short.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||||
|
time.sleep(2.3)
|
||||||
|
short.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||||
|
short.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=actor)
|
||||||
|
print("PASS: SESSION_TTL_SECONDS=2; valid then expired token rejected", flush=True)
|
||||||
|
finally:
|
||||||
|
command(["docker", "rm", "-f", name], True)
|
||||||
|
print("PASS: grade-3 verification complete", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Lab 1: a single-process, in-memory messenger."""
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import re
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
class APIError(Exception):
|
||||||
|
def __init__(self, status, code, message):
|
||||||
|
self.status, self.code, self.message = status, code, message
|
||||||
|
|
||||||
|
|
||||||
|
def invalid():
|
||||||
|
return APIError(400, "invalid_request", "Invalid request")
|
||||||
|
|
||||||
|
|
||||||
|
def uuid_value(value):
|
||||||
|
if not isinstance(value, str) or not re.fullmatch(
|
||||||
|
r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", value
|
||||||
|
):
|
||||||
|
raise invalid()
|
||||||
|
return str(UUID(value))
|
||||||
|
|
||||||
|
|
||||||
|
def string_value(value, maximum):
|
||||||
|
if (not isinstance(value, str) or not 1 <= len(value) <= maximum
|
||||||
|
or not value.strip() or "\x00" in value or any(0xD800 <= ord(c) <= 0xDFFF for c in value)):
|
||||||
|
raise invalid()
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def fields(body, expected):
|
||||||
|
if not isinstance(body, dict) or set(body) != set(expected):
|
||||||
|
raise invalid()
|
||||||
|
|
||||||
|
|
||||||
|
def unique_object(pairs):
|
||||||
|
result = {}
|
||||||
|
for key, value in pairs:
|
||||||
|
if key in result:
|
||||||
|
raise invalid()
|
||||||
|
result[key] = value
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def reject_constant(value):
|
||||||
|
raise invalid()
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""PostgreSQL configuration and transactional, versioned migrations."""
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from psycopg_pool import ConnectionPool
|
||||||
|
|
||||||
|
|
||||||
|
def database_url():
|
||||||
|
filename = os.environ.get("DATABASE_URL_FILE")
|
||||||
|
return Path(filename).read_text().strip() if filename else os.environ["DATABASE_URL"]
|
||||||
|
|
||||||
|
|
||||||
|
def migrate():
|
||||||
|
with psycopg.connect(database_url(), connect_timeout=3) as conn:
|
||||||
|
conn.execute("SELECT pg_advisory_xact_lock(2026002)")
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations "
|
||||||
|
"(version text PRIMARY KEY, checksum text NOT NULL)")
|
||||||
|
for path in sorted((Path(__file__).resolve().parents[1] / "migrations").glob("*.sql")):
|
||||||
|
sql = path.read_text(encoding="utf-8")
|
||||||
|
checksum = hashlib.sha256(sql.encode()).hexdigest()
|
||||||
|
old = conn.execute("SELECT checksum FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
|
||||||
|
if old:
|
||||||
|
if old[0] != checksum:
|
||||||
|
raise RuntimeError("Applied migration checksum changed")
|
||||||
|
continue
|
||||||
|
conn.execute(sql)
|
||||||
|
conn.execute("INSERT INTO schema_migrations VALUES (%s,%s)", (path.name, checksum))
|
||||||
|
conn.execute("INSERT INTO settings VALUES ('cursor_key',%s) ON CONFLICT DO NOTHING", (secrets.token_hex(32),))
|
||||||
|
|
||||||
|
|
||||||
|
def pool():
|
||||||
|
return ConnectionPool(database_url(), min_size=1, max_size=8, timeout=2,
|
||||||
|
max_waiting=32, open=True, check=ConnectionPool.check_connection,
|
||||||
|
kwargs={"connect_timeout": 3, "row_factory": dict_row,
|
||||||
|
"options": "-c timezone=UTC -c statement_timeout=3000 -c lock_timeout=2000"})
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
migrate()
|
||||||
|
print("PASS: migrations applied")
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"""Container readiness probe; exits nonzero on failure."""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from urllib.request import ProxyHandler, build_opener
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
host = os.environ.get("APP_HOST", "0.0.0.0")
|
||||||
|
if host == "0.0.0.0":
|
||||||
|
host = "127.0.0.1"
|
||||||
|
port = int(os.environ.get("APP_PORT", "8080"))
|
||||||
|
with build_opener(ProxyHandler({})).open(f"http://{host}:{port}/health/ready", timeout=2) as response:
|
||||||
|
if response.status != 200 or json.load(response) != {"status": "ok"}:
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Signed, resource-bound keyset cursors, inherited from lab1."""
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from .common import invalid
|
||||||
|
|
||||||
|
class Pagination:
|
||||||
|
def cursor(self, scope, record):
|
||||||
|
payload = json.dumps([scope, record["created_at"], record["id"]], separators=(",", ":")).encode()
|
||||||
|
signature = hmac.digest(self.cursor_key, payload, "sha256")
|
||||||
|
return base64.urlsafe_b64encode(signature + payload).decode().rstrip("=")
|
||||||
|
|
||||||
|
def decode_page(self, query, scope):
|
||||||
|
if set(query) - {"limit", "cursor"} or any(len(v) != 1 for v in query.values()):
|
||||||
|
raise invalid()
|
||||||
|
limit = query.get("limit", ["50"])[0]
|
||||||
|
if not re.fullmatch(r"[0-9]{1,3}", limit) or not 1 <= int(limit) <= 100:
|
||||||
|
raise invalid()
|
||||||
|
limit = int(limit)
|
||||||
|
after = None
|
||||||
|
if "cursor" in query:
|
||||||
|
token = query["cursor"][0]
|
||||||
|
if not re.fullmatch(r"[A-Za-z0-9_-]{1,1024}", token):
|
||||||
|
raise invalid()
|
||||||
|
try:
|
||||||
|
raw = base64.b64decode(token + "=" * (-len(token) % 4), altchars=b"-_", validate=True)
|
||||||
|
signature, payload = raw[:32], raw[32:]
|
||||||
|
if not hmac.compare_digest(signature, hmac.digest(self.cursor_key, payload, "sha256")):
|
||||||
|
raise invalid()
|
||||||
|
resource, created, record_id = json.loads(payload)
|
||||||
|
if resource != scope:
|
||||||
|
raise invalid()
|
||||||
|
after = (created, record_id)
|
||||||
|
except (ValueError, UnicodeError, binascii.Error):
|
||||||
|
raise invalid() from None
|
||||||
|
return limit, after
|
||||||
+181
@@ -0,0 +1,181 @@
|
|||||||
|
"""Lab1 HTTP transport with persistent lab2 operations. Run: python -m src.server."""
|
||||||
|
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import signal
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from urllib.parse import parse_qs, urlsplit
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
|
||||||
|
from .common import APIError, invalid, unique_object, reject_constant
|
||||||
|
from .store import Store
|
||||||
|
from .database import migrate
|
||||||
|
|
||||||
|
|
||||||
|
LOG = logging.getLogger("messenger")
|
||||||
|
MAX_BODY = 64 * 1024
|
||||||
|
SHUTDOWN_SECONDS = 5
|
||||||
|
|
||||||
|
|
||||||
|
class Server(ThreadingHTTPServer):
|
||||||
|
daemon_threads = True
|
||||||
|
request_queue_size = 128
|
||||||
|
|
||||||
|
def __init__(self, address):
|
||||||
|
self.store = Store()
|
||||||
|
self.stopping = threading.Event()
|
||||||
|
self.workers = set()
|
||||||
|
self.workers_lock = threading.Lock()
|
||||||
|
super().__init__(address, Handler)
|
||||||
|
self.timeout = 0.2
|
||||||
|
|
||||||
|
def process_request_thread(self, request, client_address):
|
||||||
|
worker = threading.current_thread()
|
||||||
|
with self.workers_lock:
|
||||||
|
self.workers.add(worker)
|
||||||
|
try:
|
||||||
|
super().process_request_thread(request, client_address)
|
||||||
|
finally:
|
||||||
|
with self.workers_lock:
|
||||||
|
self.workers.discard(worker)
|
||||||
|
|
||||||
|
def handle_error(self, request, client_address):
|
||||||
|
LOG.error("connection_handler_failed")
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
server_version = "Messenger"
|
||||||
|
sys_version = ""
|
||||||
|
|
||||||
|
def setup(self):
|
||||||
|
super().setup()
|
||||||
|
self.connection.settimeout(2)
|
||||||
|
|
||||||
|
def log_message(self, format, *args):
|
||||||
|
# Base handler includes raw paths and possibly user-supplied text.
|
||||||
|
pass
|
||||||
|
|
||||||
|
def send_error(self, code, message=None, explain=None):
|
||||||
|
self.request_id = getattr(self, "request_id", str(uuid4()))
|
||||||
|
self.reply(400, {"error": {"code": "invalid_request", "message": "Invalid HTTP request", "request_id": self.request_id}})
|
||||||
|
|
||||||
|
def read_body(self):
|
||||||
|
if self.headers.get_content_type() != "application/json":
|
||||||
|
raise APIError(415, "unsupported_media_type", "Expected application/json")
|
||||||
|
lengths = self.headers.get_all("Content-Length", [])
|
||||||
|
if self.headers.get("Transfer-Encoding") or len(lengths) != 1 or not re.fullmatch(r"[0-9]{1,10}", lengths[0]):
|
||||||
|
raise invalid()
|
||||||
|
size = int(lengths[0])
|
||||||
|
if size > MAX_BODY:
|
||||||
|
raise APIError(413, "payload_too_large", "Request exceeds 65536 bytes")
|
||||||
|
try:
|
||||||
|
raw = self.rfile.read(size)
|
||||||
|
if len(raw) != size:
|
||||||
|
raise invalid()
|
||||||
|
return json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object, parse_constant=reject_constant)
|
||||||
|
except (ValueError, UnicodeError, RecursionError, TimeoutError):
|
||||||
|
raise invalid() from None
|
||||||
|
|
||||||
|
def reply(self, status, body):
|
||||||
|
encoded = b"" if status == 204 else json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||||
|
self.send_response(status)
|
||||||
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||||
|
self.send_header("Content-Length", str(len(encoded)))
|
||||||
|
self.send_header("X-Request-Id", self.request_id)
|
||||||
|
if status == 401:
|
||||||
|
challenge = 'Basic realm="messenger", charset="UTF-8"' if urlsplit(self.path).path == "/api/v1/auth/sessions" else 'Bearer realm="messenger"'
|
||||||
|
self.send_header("WWW-Authenticate", challenge)
|
||||||
|
self.send_header("Connection", "close")
|
||||||
|
self.end_headers()
|
||||||
|
self.close_connection = True
|
||||||
|
self.wfile.write(encoded)
|
||||||
|
|
||||||
|
def handle_api(self):
|
||||||
|
started = time.monotonic()
|
||||||
|
self.request_id = str(uuid4())
|
||||||
|
status = 500
|
||||||
|
try:
|
||||||
|
server = self.server
|
||||||
|
assert isinstance(server, Server)
|
||||||
|
if server.stopping.is_set():
|
||||||
|
raise APIError(503, "unavailable", "Server is stopping")
|
||||||
|
parsed = urlsplit(self.path)
|
||||||
|
path = parsed.path
|
||||||
|
if path in ("/health/live", "/health/ready") and self.command == "GET":
|
||||||
|
if path == "/health/ready":
|
||||||
|
server.store.ready()
|
||||||
|
status, body = 200, {"status": "ok"}
|
||||||
|
else:
|
||||||
|
store = server.store
|
||||||
|
public = (path, self.command) in (("/api/v1/users", "POST"), ("/api/v1/auth/sessions", "POST"))
|
||||||
|
actor = None if public else store.authenticate(self.headers.get("Authorization"))
|
||||||
|
cached_body = None
|
||||||
|
if path == "/api/v1/auth/sessions" and self.command == "POST":
|
||||||
|
if self.headers.get("Transfer-Encoding") or self.headers.get("Content-Length", "0") != "0":
|
||||||
|
raise invalid()
|
||||||
|
status, body = store.login(self.headers.get("Authorization"))
|
||||||
|
else:
|
||||||
|
if self.command == "POST":
|
||||||
|
match = re.fullmatch(r"/api/v1/chats/([^/]+)/messages", path)
|
||||||
|
if match:
|
||||||
|
store.check_chat(match[1], actor)
|
||||||
|
cached_body = self.read_body()
|
||||||
|
query = parse_qs(parsed.query, keep_blank_values=True, max_num_fields=10)
|
||||||
|
status, body = store.dispatch(self.command, path, query, actor, lambda: cached_body)
|
||||||
|
except APIError as exc:
|
||||||
|
status = exc.status
|
||||||
|
body = {"error": {"code": exc.code, "message": exc.message, "request_id": self.request_id}}
|
||||||
|
except (psycopg.OperationalError, psycopg.InterfaceError):
|
||||||
|
status = 503
|
||||||
|
body = {"error": {"code": "unavailable", "message": "Storage unavailable", "request_id": self.request_id}}
|
||||||
|
except ValueError:
|
||||||
|
status = 400
|
||||||
|
body = {"error": {"code": "invalid_request", "message": "Invalid request", "request_id": self.request_id}}
|
||||||
|
except Exception as exc:
|
||||||
|
LOG.error("request_failed request_id=%s exception=%s", self.request_id, type(exc).__name__)
|
||||||
|
body = {"error": {"code": "internal_error", "message": "Internal error", "request_id": self.request_id}}
|
||||||
|
try:
|
||||||
|
self.reply(status, body)
|
||||||
|
except OSError:
|
||||||
|
LOG.info("client_disconnected request_id=%s", self.request_id)
|
||||||
|
finally:
|
||||||
|
LOG.info("request request_id=%s method=%s status=%d duration_ms=%.3f", self.request_id, self.command, status, (time.monotonic() - started) * 1000)
|
||||||
|
|
||||||
|
do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = do_OPTIONS = handle_api
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||||
|
migrate()
|
||||||
|
server = Server((os.environ.get("APP_HOST", "0.0.0.0"), int(os.environ.get("APP_PORT", "8080"))))
|
||||||
|
|
||||||
|
def stop(signum, frame):
|
||||||
|
server.stopping.set()
|
||||||
|
|
||||||
|
signal.signal(signal.SIGTERM, stop)
|
||||||
|
signal.signal(signal.SIGINT, stop)
|
||||||
|
LOG.info("started host=%s port=%d env=%s", *server.server_address, os.environ.get("APP_ENV", "lab"))
|
||||||
|
try:
|
||||||
|
while not server.stopping.is_set():
|
||||||
|
server.handle_request()
|
||||||
|
finally:
|
||||||
|
server.stopping.set()
|
||||||
|
server.server_close()
|
||||||
|
LOG.info("shutdown_started listener_closed=true budget_seconds=%d", SHUTDOWN_SECONDS)
|
||||||
|
deadline = time.monotonic() + SHUTDOWN_SECONDS
|
||||||
|
with server.workers_lock:
|
||||||
|
workers = list(server.workers)
|
||||||
|
for worker in workers:
|
||||||
|
worker.join(max(0, deadline - time.monotonic()))
|
||||||
|
server.store.pool.close()
|
||||||
|
LOG.info("shutdown_complete unfinished_requests=%d", sum(w.is_alive() for w in workers))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+180
@@ -0,0 +1,180 @@
|
|||||||
|
"""Persistent implementation of lab1 operations and lab2 sessions."""
|
||||||
|
import base64
|
||||||
|
from datetime import datetime
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
|
||||||
|
from .common import APIError, fields, invalid, string_value, uuid_value
|
||||||
|
from .database import pool
|
||||||
|
from .pagination import Pagination
|
||||||
|
|
||||||
|
|
||||||
|
def record(row):
|
||||||
|
return {k: (str(v) if isinstance(v, UUID) else
|
||||||
|
v.isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||||
|
if isinstance(v, datetime) else v) for k, v in row.items()}
|
||||||
|
|
||||||
|
|
||||||
|
def password_hash(password, salt=None):
|
||||||
|
salt = salt or secrets.token_hex(16)
|
||||||
|
derived = hashlib.scrypt(password.encode("utf-8"), salt=bytes.fromhex(salt),
|
||||||
|
n=16384, r=8, p=1, dklen=32)
|
||||||
|
return "scrypt$16384$8$1$" + salt + "$" + derived.hex()
|
||||||
|
|
||||||
|
|
||||||
|
def unauthorized():
|
||||||
|
return APIError(401, "unauthorized", "Valid credentials required")
|
||||||
|
|
||||||
|
|
||||||
|
class Store(Pagination):
|
||||||
|
def __init__(self):
|
||||||
|
self.pool = pool()
|
||||||
|
self.ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||||
|
if self.ttl <= 0:
|
||||||
|
raise ValueError("SESSION_TTL_SECONDS must be positive")
|
||||||
|
with self.pool.connection() as conn:
|
||||||
|
self.cursor_key = bytes.fromhex(conn.execute("SELECT value FROM settings WHERE key='cursor_key'").fetchone()["value"])
|
||||||
|
self.dummy_hash = password_hash("dummy-password-not-a-user")
|
||||||
|
|
||||||
|
def ready(self):
|
||||||
|
with self.pool.connection() as conn:
|
||||||
|
conn.execute("SELECT 1 FROM schema_migrations LIMIT 1").fetchone()
|
||||||
|
|
||||||
|
def authenticate(self, header):
|
||||||
|
if not isinstance(header, str) or not re.fullmatch(r"(?i:Bearer) [A-Za-z0-9_-]{43}", header):
|
||||||
|
raise unauthorized()
|
||||||
|
digest = hashlib.sha256(header.split(" ", 1)[1].encode()).hexdigest()
|
||||||
|
with self.pool.connection() as conn:
|
||||||
|
row = conn.execute("SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at>clock_timestamp()", (digest,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise unauthorized()
|
||||||
|
return (str(row["user_id"]), digest)
|
||||||
|
|
||||||
|
def login(self, header):
|
||||||
|
try:
|
||||||
|
scheme, encoded = header.split(" ", 1)
|
||||||
|
if scheme.lower() != "basic":
|
||||||
|
raise ValueError()
|
||||||
|
username, password = base64.b64decode(encoded, validate=True).decode("utf-8").split(":", 1)
|
||||||
|
if not re.fullmatch(r"[a-z0-9_]{3,32}", username) or not 12 <= len(password) <= 128:
|
||||||
|
raise ValueError()
|
||||||
|
except (AttributeError, ValueError, UnicodeError):
|
||||||
|
raise unauthorized() from None
|
||||||
|
with self.pool.connection() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
|
||||||
|
expected = row["password_hash"] if row else self.dummy_hash
|
||||||
|
actual = password_hash(password, expected.split("$")[4])
|
||||||
|
if not hmac.compare_digest(actual, expected) or row is None:
|
||||||
|
raise unauthorized()
|
||||||
|
del row["password_hash"]
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||||
|
with self.pool.connection() as conn:
|
||||||
|
expiry = conn.execute("INSERT INTO sessions VALUES (%s,%s,clock_timestamp()+%s*interval '1 second') RETURNING expires_at", (digest, row["id"], self.ttl)).fetchone()
|
||||||
|
return 201, {"token": token, "token_type": "Bearer", "expires_at": record(expiry)["expires_at"], "user": record(row)}
|
||||||
|
|
||||||
|
def chat(self, conn, value, actor, lock=False):
|
||||||
|
chat_id = uuid_value(value)
|
||||||
|
row = conn.execute("SELECT c.* FROM chats c WHERE c.id=%s AND EXISTS "
|
||||||
|
"(SELECT 1 FROM memberships m WHERE m.chat_id=c.id AND m.user_id=%s)" +
|
||||||
|
(" FOR UPDATE OF c" if lock else ""), (chat_id, actor[0])).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise APIError(404, "not_found", "Object not found")
|
||||||
|
row = record(row)
|
||||||
|
row["member_ids"] = [str(m["user_id"]) for m in conn.execute("SELECT user_id FROM memberships WHERE chat_id=%s ORDER BY ordinal", (chat_id,))]
|
||||||
|
return row
|
||||||
|
|
||||||
|
def check_chat(self, value, actor):
|
||||||
|
with self.pool.connection() as conn:
|
||||||
|
self.chat(conn, value, actor)
|
||||||
|
|
||||||
|
def page(self, conn, query, scope, table, actor=None, chat_id=None):
|
||||||
|
limit, after = self.decode_page(query, scope)
|
||||||
|
# Table and predicate are selected internally, never supplied by a client.
|
||||||
|
if table == "messages":
|
||||||
|
sql = "SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=%s"
|
||||||
|
params = [chat_id]
|
||||||
|
else:
|
||||||
|
sql = "SELECT c.* FROM chats c WHERE EXISTS (SELECT 1 FROM memberships m WHERE m.chat_id=c.id AND m.user_id=%s)"
|
||||||
|
params = [actor[0]]
|
||||||
|
if after:
|
||||||
|
sql += " AND (created_at,id)>(%s::timestamptz,%s::uuid)"
|
||||||
|
params.extend(after)
|
||||||
|
sql += " ORDER BY created_at,id LIMIT %s"
|
||||||
|
params.append(limit + 1)
|
||||||
|
rows = [record(r) for r in conn.execute(sql, params)]
|
||||||
|
items = rows[:limit]
|
||||||
|
if table == "chats":
|
||||||
|
items = [self.chat(conn, r["id"], actor) for r in items]
|
||||||
|
return {"items": items, "next_cursor": self.cursor(scope, items[-1]) if len(rows) > limit else None}
|
||||||
|
|
||||||
|
def dispatch(self, method, path, query, actor, read_body):
|
||||||
|
if path == "/api/v1/users" and method == "POST":
|
||||||
|
body = read_body()
|
||||||
|
fields(body, ("username", "display_name", "password"))
|
||||||
|
username = body["username"]
|
||||||
|
if not isinstance(username, str) or not re.fullmatch(r"[a-z0-9_]{3,32}", username):
|
||||||
|
raise invalid()
|
||||||
|
display = string_value(body["display_name"], 100)
|
||||||
|
password = string_value(body["password"], 128)
|
||||||
|
if len(password) < 12:
|
||||||
|
raise invalid()
|
||||||
|
hashed = password_hash(password)
|
||||||
|
try:
|
||||||
|
with self.pool.connection() as conn:
|
||||||
|
row = conn.execute("INSERT INTO users (id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at", (uuid4(), username, display, hashed)).fetchone()
|
||||||
|
return 201, record(row)
|
||||||
|
except psycopg.errors.UniqueViolation:
|
||||||
|
raise APIError(409, "conflict", "Username already exists") from None
|
||||||
|
with self.pool.connection() as conn:
|
||||||
|
if path == "/api/v1/auth/sessions/current" and method == "DELETE":
|
||||||
|
deleted = conn.execute("DELETE FROM sessions WHERE token_hash=%s RETURNING user_id", (actor[1],)).fetchone()
|
||||||
|
if not deleted:
|
||||||
|
raise unauthorized()
|
||||||
|
return 204, None
|
||||||
|
if path == "/api/v1/users/me" and method == "GET":
|
||||||
|
return 200, record(conn.execute("SELECT id,username,display_name,created_at FROM users WHERE id=%s", (actor[0],)).fetchone())
|
||||||
|
if path == "/api/v1/chats":
|
||||||
|
if method == "GET":
|
||||||
|
return 200, self.page(conn, query, "chats:" + actor[0], "chats", actor=actor)
|
||||||
|
if method == "POST":
|
||||||
|
body = read_body()
|
||||||
|
fields(body, ("title", "member_ids"))
|
||||||
|
title = string_value(body["title"], 100)
|
||||||
|
members = body["member_ids"]
|
||||||
|
if not isinstance(members, list) or not 1 <= len(members) <= 100:
|
||||||
|
raise invalid()
|
||||||
|
members = [uuid_value(m) for m in members]
|
||||||
|
if len(set(members)) != len(members) or actor[0] not in members:
|
||||||
|
raise invalid()
|
||||||
|
row = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING *", (uuid4(), title)).fetchone()
|
||||||
|
existing = conn.execute("SELECT id FROM users WHERE id=ANY(%s::uuid[])", (members,)).fetchall()
|
||||||
|
if len(existing) != len(members):
|
||||||
|
raise invalid() # Rolls back the chat INSERT as well.
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.executemany("INSERT INTO memberships VALUES (%s,%s,%s)", [(row["id"], m, i) for i, m in enumerate(members)])
|
||||||
|
return 201, dict(record(row), member_ids=members)
|
||||||
|
match = re.fullmatch(r"/api/v1/chats/([^/]+)(/messages)?", path)
|
||||||
|
if match:
|
||||||
|
chat = self.chat(conn, match[1], actor, lock=method == "POST")
|
||||||
|
if match[2] is None and method == "GET":
|
||||||
|
return 200, chat
|
||||||
|
if match[2] == "/messages":
|
||||||
|
if method == "GET":
|
||||||
|
return 200, self.page(conn, query, "messages:" + chat["id"], "messages", chat_id=chat["id"])
|
||||||
|
if method == "POST":
|
||||||
|
body = read_body()
|
||||||
|
fields(body, ("text",))
|
||||||
|
text = string_value(body["text"], 4000)
|
||||||
|
row = conn.execute("INSERT INTO messages VALUES (%s,%s,%s,%s,GREATEST(clock_timestamp(), "
|
||||||
|
"COALESCE((SELECT created_at+interval '1 microsecond' FROM messages "
|
||||||
|
"WHERE chat_id=%s ORDER BY created_at DESC,id DESC LIMIT 1),clock_timestamp()))) RETURNING *",
|
||||||
|
(uuid4(), chat["id"], actor[0], text, chat["id"])).fetchone()
|
||||||
|
return 201, record(row)
|
||||||
|
raise APIError(404, "not_found", "Object not found")
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""Own HTTP checks, separate from the unchanged public tests."""
|
||||||
|
import base64
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
from urllib.parse import quote
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||||
|
from client import Client
|
||||||
|
|
||||||
|
|
||||||
|
class API(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.c = Client(os.environ.get("BASE_URL", "http://127.0.0.1:18082"))
|
||||||
|
self.a, self.b, self.e, self.chat = self.c.bootstrap()
|
||||||
|
self.path = "/api/v1/chats/" + self.chat["id"]
|
||||||
|
|
||||||
|
def test_registration_validation(self):
|
||||||
|
body = dict(self.a["registration"], username="u_" + uuid4().hex[:16])
|
||||||
|
for password in ("short", "x" * 129, 123, None):
|
||||||
|
self.c.call("POST", "/api/v1/users", 400, body=dict(body, password=password))
|
||||||
|
self.c.call("POST", "/api/v1/users", 400, body=dict(body, extra=True))
|
||||||
|
|
||||||
|
def test_unicode_password_with_colon_and_max_length(self):
|
||||||
|
username = "u_" + uuid4().hex[:16]
|
||||||
|
password = "Я:🔐" + "б" * 125
|
||||||
|
body = {"username": username, "display_name": "Имя 👋", "password": password}
|
||||||
|
user = self.c.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||||
|
credential = base64.b64encode((username + ":" + password).encode()).decode()
|
||||||
|
result = self.c.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + credential}, schema="Session")["json"]
|
||||||
|
self.assertEqual(user, result["user"])
|
||||||
|
self.assertGreaterEqual(len(base64.urlsafe_b64decode(result["token"] + "=")), 32)
|
||||||
|
|
||||||
|
def test_bad_credentials_and_schemes(self):
|
||||||
|
for credential in ("Basic ***", "Bearer token", "", "Basic " + base64.b64encode(b"missing:wrong-password").decode()):
|
||||||
|
self.c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": credential})
|
||||||
|
self.c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": self.a["id"]})
|
||||||
|
|
||||||
|
def test_logout_only_revokes_current_session(self):
|
||||||
|
body = self.a["registration"]
|
||||||
|
credential = base64.b64encode((body["username"] + ":" + body["password"]).encode()).decode()
|
||||||
|
other = self.c.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + credential}, schema="Session")["json"]
|
||||||
|
self.c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.a)
|
||||||
|
self.c.call("GET", "/api/v1/users/me", 401, actor=self.a)
|
||||||
|
self.c.call("GET", "/api/v1/users/me", actor={"token": other["token"]}, schema="User")
|
||||||
|
|
||||||
|
def test_chat_atomic_invalid_members(self):
|
||||||
|
before = self.c.call("GET", "/api/v1/chats?limit=100", actor=self.a, schema="ChatPage")["json"]
|
||||||
|
for members in ([self.a["id"], str(uuid4())], [self.a["id"], self.a["id"]], [self.b["id"]]):
|
||||||
|
self.c.call("POST", "/api/v1/chats", 400, actor=self.a, body={"title": "rollback", "member_ids": members})
|
||||||
|
after = self.c.call("GET", "/api/v1/chats?limit=100", actor=self.a, schema="ChatPage")["json"]
|
||||||
|
self.assertEqual(before, after)
|
||||||
|
|
||||||
|
def test_username_race(self):
|
||||||
|
body = dict(self.a["registration"], username="race_" + uuid4().hex[:16])
|
||||||
|
def register(_):
|
||||||
|
return Client(self.c.base).call("POST", "/api/v1/users", [201, 409], body=body)["status"]
|
||||||
|
with ThreadPoolExecutor(max_workers=6) as pool:
|
||||||
|
statuses = list(pool.map(register, range(6)))
|
||||||
|
self.assertEqual(statuses.count(201), 1)
|
||||||
|
self.assertEqual(statuses.count(409), 5)
|
||||||
|
|
||||||
|
def test_concurrent_messages_and_keyset(self):
|
||||||
|
def send(i):
|
||||||
|
return Client(self.c.base).message(self.a, self.chat, "Поток " + str(i))["json"]
|
||||||
|
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||||
|
sent = list(pool.map(send, range(40)))
|
||||||
|
items, cursor = [], None
|
||||||
|
while True:
|
||||||
|
page = self.c.call("GET", self.path + "/messages?limit=7" + ("&cursor=" + quote(cursor) if cursor else ""), actor=self.b, schema="MessagePage")["json"]
|
||||||
|
items.extend(page["items"])
|
||||||
|
cursor = page["next_cursor"]
|
||||||
|
if cursor is None:
|
||||||
|
break
|
||||||
|
self.assertEqual(len(items), 40)
|
||||||
|
self.assertEqual({x["id"] for x in items}, {x["id"] for x in sent})
|
||||||
|
self.assertEqual(items, sorted(sent, key=lambda x: (x["created_at"], x["id"])))
|
||||||
|
|
||||||
|
def test_cursor_scope_and_tampering(self):
|
||||||
|
for i in range(3):
|
||||||
|
self.c.message(self.a, self.chat, str(i))
|
||||||
|
page = self.c.call("GET", self.path + "/messages?limit=1", actor=self.a, schema="MessagePage")["json"]
|
||||||
|
cursor = page["next_cursor"]
|
||||||
|
self.c.call("GET", "/api/v1/chats?cursor=" + quote(cursor), 400, actor=self.a)
|
||||||
|
other = self.c.call("POST", "/api/v1/chats", 201, actor=self.a, body={"title": "Другой", "member_ids": [self.a["id"]]}, schema="Chat")["json"]
|
||||||
|
self.c.call("GET", "/api/v1/chats/" + other["id"] + "/messages?cursor=" + quote(cursor), 400, actor=self.a)
|
||||||
|
self.c.call("GET", self.path + "/messages?cursor=" + quote("X" + cursor[1:]), 400, actor=self.a)
|
||||||
|
|
||||||
|
def test_json_and_sender_validation(self):
|
||||||
|
for raw in (b'{"text":"a","text":"b"}', b'{"text":NaN}', b'{', b'{"text":"\\u0000"}'):
|
||||||
|
self.c.call("POST", self.path + "/messages", 400, actor=self.a, raw=raw, headers={"Content-Type": "application/json"})
|
||||||
|
self.c.call("POST", self.path + "/messages", 400, actor=self.a, body={"text": "hello", "sender_id": self.b["id"]})
|
||||||
|
self.c.call("POST", self.path + "/messages", 400, actor=self.a, body={"text": " "})
|
||||||
|
page = self.c.call("GET", self.path + "/messages", actor=self.a, schema="MessagePage")["json"]
|
||||||
|
self.assertEqual(page["items"], [])
|
||||||
|
|
||||||
|
def test_access_before_payload_validation(self):
|
||||||
|
self.c.call("POST", self.path + "/messages", 404, actor=self.e, body={})
|
||||||
|
self.c.call("POST", self.path + "/messages", 401, body={})
|
||||||
|
self.c.call("GET", self.path, 404, actor=self.e)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in New Issue
Block a user