2 Commits
Author SHA1 Message Date
ferraronp 1e686a5ce0 docs: finalize lab2 report with verified results
Skeleton contracts / contracts (pull_request) Canceled after 0s
2026-10-23 18:45:50 +03:00
ferraronp 5dd32a77ac Implement lab2 PostgreSQL authentication and Redis sessions 2026-10-23 18:33:06 +03:00
23 changed files with 1128 additions and 55 deletions
+10 -15
View File
@@ -3,18 +3,13 @@
.env .env
.env.* .env.*
!.env.example !.env.example
secrets *.md
certs __pycache__/
volumes *.py[cod]
data .venv/
backups .pytest_cache/
*.key .mypy_cache/
*.pem evidence/
*.p12 tests/
*.pfx *.zip
*.jks *.sqlite
.venv
__pycache__
node_modules
evidence
.DS_Store
+5 -10
View File
@@ -1,11 +1,6 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env. # Copy to .env, change the synthetic lab credentials, never commit .env.
# These are logical interface suggestions; map actual framework names in REPORT.md. POSTGRES_DB=messenger
APP_HOST=0.0.0.0 POSTGRES_USER=lab_user
APP_PORT=8080 POSTGRES_PASSWORD=CHANGE_ME_TO_A_LOCAL_RANDOM_PASSWORD
APP_ENV=lab
SESSION_TTL_SECONDS=3600 SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values. DB_POOL_MAX=8
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
+3
View File
@@ -0,0 +1,3 @@
* text=auto
# Shell scripts must have Unix line endings for Docker/Linux/WSL.
*.sh text eol=lf
+4 -9
View File
@@ -17,15 +17,10 @@ backups/
.venv/ .venv/
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
node_modules/ .pytest_cache/
dist/ .mypy_cache/
build/ evidence/*.json
target/ evidence/*.txt
bin/
obj/
coverage/
*.log
.DS_Store
.idea/ .idea/
.vscode/ .vscode/
# Keep small, sanitized evidence summaries in evidence/ under version control. # Keep small, sanitized evidence summaries in evidence/ under version control.
+19
View File
@@ -0,0 +1,19 @@
FROM python:3.12.12-slim-bookworm
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
APP_HOST=0.0.0.0 \
APP_PORT=8080
WORKDIR /app
RUN groupadd --system app && useradd --system --gid app --create-home app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
COPY db ./db
COPY scripts/explain_history.py scripts/rollback_check.py ./scripts/
USER app
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2).read()" || exit 1
CMD ["python", "-m", "app"]
+14 -1
View File
@@ -1,4 +1,4 @@
PYTHON ?= python3 PYTHON ?= python
BASE_URL ?= http://localhost:8080 BASE_URL ?= http://localhost:8080
CA_FILE ?= CA_FILE ?=
ACTION_SCRIPT ?= ACTION_SCRIPT ?=
@@ -24,3 +24,16 @@ load:
test-persistence: test-persistence:
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
.PHONY: test-own test-expiry test-dependencies
test-own:
$(PYTHON) tests/extra.py
# Run only after starting API with SESSION_TTL_SECONDS=2; use an isolated test stack.
test-expiry:
$(PYTHON) tests/expiry.py
# Stops PostgreSQL and Redis; must run only against your dedicated lab stack.
test-dependencies:
$(PYTHON) tests/dependency.py
+128 -20
View File
@@ -1,37 +1,145 @@
# Отчёт — лабораторная 2 # Отчёт — лабораторная 2
- Автор, группа: TODO - Автор, группа: Авзалов Артур Марсович, БПИ2301
- Целевая оценка; выбранный трек 5, если нужен: TODO - Целевая оценка: **4** (трек 5 не заявлен)
- Commit/PR: TODO после публикации - Коммит и MR: идентификатор коммита и ссылка доступны в истории соответствующего merge request в Gitea
- Использованные источники, библиотеки и помощь ИИ: TODO - Дата локальной проверки: **23 октября 2026 года**, Windows PowerShell + Docker Desktop
- Источники: FastAPI, Pydantic, PostgreSQL/psycopg, Argon2id (argon2-cffi), Redis, Docker Compose. ChatGPT использовался для помощи в реализации приложения, тестовых скриптов и документации; проверки ниже выполнены локально студентом.
> **Статус доказательств (23.10.2026).** На Windows PowerShell + Docker Desktop подтверждены успешная сборка и `healthy` для API, PostgreSQL и Redis; `make check` и `make test`; public smoke после миграции `002`; дополнительные негативные тесты; защита от повреждённой Redis-сессии; persistence после перезапуска всех трёх сервисов; rollback; SQL EXPLAIN на 10 000 сообщений; TTL=2 с последующим возвратом к 3600; отказы Redis/PostgreSQL с восстановлением. Повторный запуск миграций показал `Migrations up to date`; контейнер API работает от `app` (UID 999); финальный smoke после отказов повторно прошёл. Результаты приведены по реальным выводам, полученным на машине студента. Linux/WSL persistence и чистый запуск на другой машине отдельно не проверялись.
## Запуск из чистого clone ## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. Предпосылки: Docker Desktop с Compose v2, Python 3.9+ (для запуска тестов), `make` (либо прямые вызовы `python tests/...`). Все порты внутренних сервисов закрыты с хоста; только API слушает `127.0.0.1:8080`. Синтетические credentials предназначены для изолированного локального стенда, HTTP Basic по сети вне localhost недопустим без TLS.
Windows PowerShell:
```powershell
Copy-Item .env.example .env
# Открой .env локально и поставь случайный пароль без URI-спецсимволов.
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build
docker compose --env-file .env ps
python tests/smoke.py
python tests/extra.py
python tests/redis_corruption.py
python tests/resilience.py --mode persistence --action-script scripts/restart.cmd
python tests/dependency.py
# дополнительно:
python scripts/check_contract.py
docker compose --env-file .env run --rm migrate
docker compose --env-file .env exec -T api id
```
Linux/WSL:
```sh
cp .env.example .env
# Установить локальный пароль в .env (не коммитить)
docker compose --env-file .env up -d --build
make check
make test
make test-own
chmod +x scripts/restart.sh
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-dependencies
```
Применение миграций происходит однократным Compose-сервисом `migrate` **до запуска API**. Для отдельной проверки повторного запуска: `docker compose --env-file .env run --rm migrate` (второй запуск не должен ничего изменять). Проверить логи миграций: `docker compose --env-file .env logs migrate`.
Остановка без потери данных: `docker compose --env-file .env down` (без `-v`). Намеренно **полностью удалить** учебные данные: `docker compose --env-file .env down -v` (не запускать при persistence-проверке!). В Git не попадут `.env` и named volumes.
## Архитектура и решения ## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. ```text
Client (localhost:8080) -> FastAPI (1 worker, no mutable business state)
|-> PostgreSQL 16: users, chats, chat_members, messages
`-> Redis 7.4: session:<SHA256(token)> -> user UUID (TTL + AOF)
```
## Доказательства критериев Образ API: `python:3.12.12-slim-bookworm`, запуск от `app` (non-root); версии зависимостей зафиксированы в `requirements.txt`. PostgreSQL хранит **истину по бизнес-данным**; Redis — **единственное хранилище действующих серверных сессий** (нет локальной памяти процесса). Токен генерируется `secrets.token_urlsafe(32)` (256 бит энтропии); ключ Redis использует SHA-256 от токена, клиенту возвращается только исходное случайное значение. `EX` устанавливает TTL, `DEL` отзывает сессию. AOF с `appendfsync always` сохраняет записи на диск; named volume хранит их при рестарте. TTL при рестарте не продлевается. `FLUSHDB` сотрёт сессии — прежние токены станут недействительными; данные чатов в PostgreSQL сохранятся.
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | Пароли хранятся только как Argon2id hash с солью в PostgreSQL (`time_cost=2`, `memory_cost=19456` KiB, `parallelism=1`; библиотека `argon2-cffi`). POST `/api/v1/auth/sessions` принимает только Basic и не использует JSON body; остальные endpoint принимают только `Authorization: Bearer`. Заголовок `X-User-Id` больше не аутентифицирует. Доступ к конкретному чату дополнительно проверяется по `chat_members`; посторонний получает 404. HTTP вне локальной сети не используется.
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. В `db/migrations/001_initial.sql`: PK/FK, UNIQUE(username), UNIQUE(chat_id, user_id), позиция участников и B-tree индекс `idx_messages_chat_history(chat_id, created_at, id)`. Создание чата + участников выполняется в одной транзакции. При ошибке вставок все изменения откатываются; гонка по username отсекается ограничением UNIQUE в PostgreSQL, а не проверкой в памяти Python.
## Эксперименты и отказы В `db/migrations/002_utf8_binary_strings.sql` пользовательские `display_name`, `chats.title` и `messages.text` конвертируются без потери данных из varchar в `bytea` (сырые UTF-8 байты): PostgreSQL text/varchar не принимает U+0000, хотя семантика API допускает этот символ. Приложение проверяет максимальную длину в **Unicode code points** и UTF-8 валидность до `.encode('utf-8')`; при чтении декодирует bytes. В БД есть ограничение на длину в байтах, а проверка непустого/непробельного значения выполняется на уровне API. Это позволяет хранить `A\u0000B` без 503 и сохранить все существующие записи при миграции.
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. Чтение сообщений — keyset по `(created_at,id)`, без загрузки всей истории в Python, с `LIMIT limit+1`. Последняя запись страницы превращается в cursor; при продолжении проверяется, что запись существует и принадлежит текущему чату. При изменении истории в ходе обхода snapshot между HTTP-запросами не гарантирован. Для составного ключа времени и UUID `id` обеспечивает определённый порядок даже при совпавших метках времени.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | Пул: psycopg_pool, `max_size=DB_POOL_MAX` (по умолчанию 8), ожидание получения соединения — 3 с, время установки БД соединения — 5 с, `statement_timeout` — 5 с, Redis socket/connect timeout — 2 с. При отказе критической БД/Redis — 503, `/health/live` остаётся 200, `/health/ready` становится 503. Неизвестная/отозванная/истёкшая сессия — 401; нельзя обходить недоступный Redis по X-User-Id. API не логирует тела сообщений, токены или пароли.
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | ## Доказательства критериев (фактические прогоны на Windows)
| Критерий | Как проверяли | Наблюдение |
|----------------------------------------|--------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `make check` | `make check` | **PASS**: offline skeleton structure, local refs and Python syntax; application NOT tested |
| `make test` | `make test` | **PASS**: lab2 public API scenario; infrastructure and grading evidence remain separate |
| Compose / готовность | `docker compose --env-file .env up -d --build`, `docker compose --env-file .env ps` | API, PostgreSQL и Redis работают и `healthy`; API доступен только на `127.0.0.1:8080` |
| Public smoke после миграции `002` | `python tests/smoke.py` | **PASS**: `lab2 public API scenario; infrastructure and grading evidence remain separate.` |
| Дополнительные негативные тесты | `python tests/extra.py` | **PASS**: login body, пароль из пробелов, проверки JSON, U+0000, лимит входного массива, гонка username и др. |
| Повреждённое значение сессии | `python tests/redis_corruption.py` | **PASS**: испорченная запись отвергается `401` и удаляется |
| Persistence API + PostgreSQL + Redis | `python tests/resilience.py --mode persistence --action-script scripts/restart.cmd` | **PASS**: тот же Bearer-токен, подтверждённые сообщения и данные доступны после restart; hook завершился кодом 0. В отдельном запуске hook показал последовательную остановку API, Redis, PostgreSQL и их запуск без удаления volumes |
| Rollback | `docker compose --env-file .env exec -T api python scripts/rollback_check.py` | **PASS**: вставка чата и участников откатилась целиком после FK-ошибки |
| История 10 000 записей | `docker compose --env-file .env exec -T api python scripts/explain_history.py` | **PASS**: `Index Scan using idx_messages_chat_history`, `rows=50`, `Buffers: shared hit=5`, `Execution Time: 0.377 ms` |
| Session TTL | Временный `SESSION_TTL_SECONDS=2`, `python tests/expiry.py`, затем возвращено `3600` | **PASS**: токен после истечения получает `401`; `printenv` показал `2`, затем `3600` |
| Redis outage | `python tests/dependency.py` | **PASS**: защищённый API и readiness вернули `503`; после восстановления Redis сессия сохранилась |
| PostgreSQL outage | `python tests/dependency.py` | **PASS**: защищённый API и readiness вернули `503`; после восстановления PostgreSQL сессия сохранилась |
| Повторный запуск миграций | `docker compose --env-file .env run --rm migrate` | **PASS**: после применения `002` повторный отдельный запуск вывел `Migrations up to date`; повторных изменений нет |
| Non-root непосредственно в контейнере | `docker compose --env-file .env exec -T api id` | **PASS**: `uid=999(app) gid=999(app) groups=999(app)` |
| Последний smoke после имитации отказов | `python tests/smoke.py` | **PASS**: `lab2 public API scenario; infrastructure and grading evidence remain separate.` |
**Примечание к негативному тесту на 101 участника.** Схема `CreateChat.member_ids` содержит `max_length=100`, поэтому API отклоняет массив длины 101. Текущий `extra.py` использует 100 случайных несуществующих UUID плюс вызывающего, поэтому один этот HTTP-тест не изолирует причину `400`: такое же значение могло бы возникнуть из-за неизвестных пользователей. Это отдельно проверено ревизией схемы; при необходимости добавляется тест со 101 заранее созданным реальным пользователем.
### Короткий TTL (отдельный запуск)
Windows PowerShell **после обычных smoke/persistence**:
```powershell
$env:SESSION_TTL_SECONDS = '2'
docker compose --env-file .env up -d --no-deps --force-recreate api
python tests/expiry.py
Remove-Item Env:SESSION_TTL_SECONDS
docker compose --env-file .env up -d --no-deps --force-recreate api
```
Обоснование: переcоздание только API не удаляет PostgreSQL и Redis volumes. Тест создаёт нового пользователя, токен, спит 3.1 секунды и убеждается, что токен получил 401. После восстановления TTL=3600 повторить smoke. Для PowerShell используйте `python` (в старом skeleton `Makefile` был `python3`).
### SQL EXPLAIN (фактический вывод 23.10.2026)
Отдельная тестовая история: **10 000 сообщений**, chat_id `d94197ba-c1a1-4aa8-af1a-fd67c9138c1e`. `EXPLAIN (ANALYZE, BUFFERS)` для страницы `LIMIT 50` с keyset-условием:
```text
Limit (cost=0.29..5.30 rows=50 width=70) (actual time=0.032..0.067 rows=50 loops=1)
Buffers: shared hit=5
-> Index Scan using idx_messages_chat_history on messages (cost=0.29..501.83 rows=4999 width=70) (actual time=0.030..0.056 rows=50 loops=1)
Index Cond: ((chat_id = 'd94197ba-c1a1-4aa8-af1a-fd67c9138c1e'::uuid) AND (ROW(created_at, id) > ROW('2026-10-23 14:58:41.99321+00'::timestamp with time zone, '8da12be9-184e-42fb-b175-469e45109f3e'::uuid)))
Buffers: shared hit=5
Planning:
Buffers: shared hit=12
Planning Time: 2.458 ms
Execution Time: 0.377 ms
```
Индекс `idx_messages_chat_history(chat_id, created_at, id)` выбран планировщиком. Для конкретного чата применяется условие `(created_at, id) > (cursor_created_at, cursor_id)`; PostgreSQL читает следующую порцию истории по индексу без полного прохода с `OFFSET`. `shared hit=5` означает обращения к страницам, оказавшимся в буферном кэше. `0.377 ms` — время **серверного SQL**, а не end-to-end HTTP latency; не является гарантией под конкурентной нагрузкой или холодным кэшем. Версия PostgreSQL: образ `postgres:16.10-bookworm`; CPU/RAM-профиль хоста в ходе измерения не зафиксирован. Тестовый fixture не очищен автоматически.
## Эксперименты и отказы (23.10.2026)
| Воздействие | Ожидаем | Наблюдали |
|-------------------------------------------|--------------------------------------------------------------|-----------------------------------------------------------------------------|
| Restart API+PG+Redis без удаления volumes | Сохранены пользователи, чаты, сообщения и действующий токен | **PASS**; hook `Exit code: 0`, persistence client подтвердил прежний Bearer |
| Logout | Старый токен далее получает 401 | **PASS** в `tests/extra.py` |
| TTL=2 | Токен после 3.1 с получает 401 | **PASS**, переменная окружения затем восстановлена до 3600 |
| Stop Redis | Readiness и защищённый API 503, после запуска токен работает | **PASS** |
| Stop PostgreSQL | Readiness и защищённый API 503, после запуска токен работает | **PASS** |
| Конкурентная регистрация одного username | 1×201, 9×409 | **PASS** в `tests/extra.py` (assertion на точные количества) |
| Ошибка FK посреди транзакции | Частично созданного чата в БД нет | **PASS**, `rollback_check.py` |
| Повреждение своей записи сессии в Redis | 401, испорченный ключ удалён | **PASS**, `redis_corruption.py` |
## Ограничения и следующие шаги ## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. - Один API процесс (нет LB/реплик, это lab3). PostgreSQL и Redis — single points of failure, HA не заявлен.
- Redis недоступен — защищённые запросы возвращают 503; это корректный fail-closed выбор для сессий. `logout` при отказе Redis **не возвращает 204**: отозвать токен нельзя, API возвращает 503. Положительного кэша поверх PostgreSQL-сессий нет; Redis — единственный источник сессий. Некорректная строка вместо UUID сессии отклоняется 401 с удалением испорченного ключа.
- Нет TLS во внешней сети: тестовый стенд предназначен только для localhost и синтетических паролей.
- Хранение данных гарантируется корректным завершением/рестартом volumes; против отказа диска, утраты volumes или разрушения FS этот стенд не защищает. PostgreSQL durability зависит от fsync/WAL, Redis — от AOF.
- Автоматические сценарии и инъекция отказов не доказывают все эксплуатационные свойства. Подтверждены non-root, повторная идемпотентная миграция и финальный smoke после отказов; Linux/WSL persistence и запуск из чистого clone в другой среде отдельно не проверялись.
View File
+11
View File
@@ -0,0 +1,11 @@
import os
import uvicorn
if __name__ == "__main__":
uvicorn.run(
"app.main:app",
host=os.getenv("APP_HOST", "0.0.0.0"),
port=int(os.getenv("APP_PORT", "8080")),
workers=1,
access_log=False,
)
+493
View File
@@ -0,0 +1,493 @@
"""Lab 2: stateless HTTP API, PostgreSQL source of truth, durable Redis sessions."""
from __future__ import annotations
import base64
import binascii
import hashlib
import json
import logging
import os
import re
import secrets
import uuid
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from typing import Any
import psycopg
import redis
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
from fastapi import FastAPI, Query, Request
from fastapi.concurrency import run_in_threadpool
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from psycopg.errors import UniqueViolation
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool, PoolTimeout
from pydantic import BaseModel, ConfigDict, Field, field_validator
logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"), format="%(asctime)s %(levelname)s %(name)s %(message)s")
logger = logging.getLogger("messenger")
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}\Z")
ph = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1) # Argon2id; bounded 19 MiB/KDF.
# Dummy KDF verification on unknown users reduces username-enumeration timing leakage.
DUMMY_HASH = ph.hash("lab2-dummy-password-not-for-login")
def iso(dt: datetime) -> str:
return dt.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
class APIError(Exception):
def __init__(self, status: int, code: str, message: str):
super().__init__(message)
self.status, self.code, self.message = status, code, message
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
class CreateUser(StrictModel):
username: str
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("username")
@classmethod
def check_username(cls, v: str) -> str:
if not USERNAME_RE.fullmatch(v):
raise ValueError("invalid username")
return v
@field_validator("display_name", "password")
@classmethod
def non_blank(cls, v: str) -> str:
if not v.strip():
raise ValueError("must not be blank")
try:
v.encode("utf-8")
except UnicodeEncodeError as exc:
raise ValueError("must be valid UTF-8") from exc
return v
class CreateChat(StrictModel):
title: str = Field(min_length=1, max_length=100)
member_ids: list[str] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def non_blank(cls, v: str) -> str:
if not v.strip():
raise ValueError("blank title")
try:
v.encode("utf-8")
except UnicodeEncodeError as exc:
raise ValueError("must be valid UTF-8") from exc
return v
@field_validator("member_ids")
@classmethod
def unique(cls, v: list[str]) -> list[str]:
if len(v) != len(set(v)):
raise ValueError("duplicate members")
return v
class CreateMessage(StrictModel):
text: str = Field(min_length=1, max_length=4000)
@field_validator("text")
@classmethod
def non_blank(cls, v: str) -> str:
if not v.strip():
raise ValueError("blank message")
try:
v.encode("utf-8")
except UnicodeEncodeError as exc:
raise ValueError("must be valid UTF-8") from exc
return v
@asynccontextmanager
async def lifespan(app: FastAPI):
url = os.environ.get("DATABASE_URL")
if not url:
raise RuntimeError("DATABASE_URL must be provided (do not commit credentials)")
pool = ConnectionPool(url, min_size=1, max_size=int(os.environ.get("DB_POOL_MAX", "8")),
timeout=3, max_lifetime=1800,
kwargs={"row_factory": dict_row, "connect_timeout": 5, "options": "-c statement_timeout=5000"}, open=False)
pool.open(wait=False)
app.state.pool = pool
app.state.sessions = redis.Redis.from_url(os.environ.get("REDIS_URL", "redis://redis:6379/0"),
socket_connect_timeout=2, socket_timeout=2,
health_check_interval=10, decode_responses=True)
ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
if ttl < 1:
raise RuntimeError("SESSION_TTL_SECONDS must be >= 1")
app.state.session_ttl = ttl
try:
yield
finally:
app.state.sessions.close()
pool.close()
app = FastAPI(title="MTUCI Messenger Lab 2", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
def reqid(request: Request) -> str:
return getattr(request.state, "request_id", "unknown")
def error_response(request: Request, status: int, code: str, message: str) -> JSONResponse:
result = JSONResponse(status_code=status, content={"error": {"code": code, "message": message, "request_id": reqid(request)}})
if status == 401:
scheme = 'Basic' if request.url.path == "/api/v1/auth/sessions" else 'Bearer'
result.headers["WWW-Authenticate"] = (f'Basic realm="messenger", charset="UTF-8"' if scheme == 'Basic' else 'Bearer realm="messenger"')
return result
@app.middleware("http")
async def request_context(request: Request, call_next):
request.state.request_id = uuid.uuid4().hex
logger.info("request start id=%s method=%s path=%s", reqid(request), request.method, request.url.path)
try:
path = request.url.path
if path == "/api/v1/users/me" or path.startswith("/api/v1/chats") or path == "/api/v1/auth/sessions/current":
# Authentication precedes resource and body validation.
request.state.actor = await run_in_threadpool(_authenticate, request)
if request.method == "POST" and (path in ("/api/v1/users", "/api/v1/chats") or (path.startswith("/api/v1/chats/") and path.endswith("/messages"))):
mime = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if mime != "application/json":
raise APIError(415, "unsupported_media_type", "Content-Type must be application/json")
response = await call_next(request)
except APIError as exc:
response = error_response(request, exc.status, exc.code, exc.message)
except (psycopg.Error, PoolTimeout, redis.RedisError):
logger.warning("dependency unavailable request=%s", reqid(request))
response = error_response(request, 503, "unavailable", "Required dependency unavailable")
except Exception:
logger.exception("unexpected request error id=%s", reqid(request))
response = error_response(request, 500, "internal_error", "Internal server error")
response.headers["X-Request-Id"] = reqid(request)
logger.info("request end id=%s status=%s", reqid(request), response.status_code)
return response
@app.exception_handler(APIError)
async def api_error_handler(request: Request, exc: APIError):
return error_response(request, exc.status, exc.code, exc.message)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
return error_response(request, 400, "invalid_request", "Invalid request")
@app.exception_handler(psycopg.Error)
async def db_error_handler(request: Request, exc: psycopg.Error):
logger.warning("database error request=%s class=%s", reqid(request), type(exc).__name__)
return error_response(request, 503, "unavailable", "Required dependency unavailable")
@app.exception_handler(PoolTimeout)
async def pool_error_handler(request: Request, exc: PoolTimeout):
return error_response(request, 503, "unavailable", "Required dependency unavailable")
@app.exception_handler(redis.RedisError)
async def redis_error_handler(request: Request, exc: redis.RedisError):
return error_response(request, 503, "unavailable", "Required dependency unavailable")
@app.exception_handler(Exception)
async def unexpected_handler(request: Request, exc: Exception):
logger.exception("unexpected application error request=%s", reqid(request))
return error_response(request, 500, "internal_error", "Internal server error")
def valid_uuid(raw: str, name: str = "id") -> uuid.UUID:
try:
return uuid.UUID(raw)
except (ValueError, AttributeError, TypeError):
raise APIError(400, "invalid_request", f"Invalid {name}")
def limit_value(raw: str | None) -> int:
if raw is None:
return 50
if not re.fullmatch(r"[0-9]+", raw):
raise APIError(400, "invalid_request", "Invalid limit")
n = int(raw)
if n < 1 or n > 100:
raise APIError(400, "invalid_request", "Invalid limit")
return n
def from_db_utf8(value: bytes | memoryview) -> str:
"""Decode PostgreSQL bytea; unlike text/varchar it can contain U+0000.
The HTTP contract allows the full UTF-8 string range, including an escaped
JSON NUL. Pydantic checks Unicode code-point lengths before encoding;
the database enforces a conservative upper bound on byte length.
"""
return bytes(value).decode("utf-8")
def user_public(row: dict[str, Any]) -> dict[str, Any]:
return {"id": str(row["id"]), "username": row["username"], "display_name": from_db_utf8(row["display_name"]), "created_at": iso(row["created_at"])}
def chat_public(row: dict[str, Any]) -> dict[str, Any]:
return {"id": str(row["id"]), "title": from_db_utf8(row["title"]), "member_ids": [str(x) for x in row["member_ids"]], "created_at": iso(row["created_at"])}
def message_public(row: dict[str, Any]) -> dict[str, Any]:
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": from_db_utf8(row["text"]), "created_at": iso(row["created_at"])}
def _authenticate(request: Request) -> dict[str, Any]:
auth = request.headers.get("authorization", "")
parts = auth.split(" ", 1)
if len(parts) != 2 or parts[0].lower() != "bearer" or not parts[1] or not re.fullmatch(r"[A-Za-z0-9_-]+", parts[1]):
raise APIError(401, "unauthorized", "Unauthorized")
token = parts[1]
digest = hashlib.sha256(token.encode("ascii")).hexdigest()
redis_key = "session:" + digest
user_id = request.app.state.sessions.get(redis_key)
if user_id is None:
raise APIError(401, "unauthorized", "Unauthorized")
try:
session_uid = uuid.UUID(user_id)
except (ValueError, AttributeError, TypeError):
# Corrupted Redis contents are not an authenticated identity. Fail
# closed and delete only the broken key, never invent a user or emit 500.
request.app.state.sessions.delete(redis_key)
raise APIError(401, "unauthorized", "Unauthorized")
with request.app.state.pool.connection() as conn:
row = conn.execute("SELECT id, username, display_name, created_at FROM users WHERE id = %s", (session_uid,)).fetchone()
if row is None:
raise APIError(401, "unauthorized", "Unauthorized")
actor = user_public(row)
request.state.session_digest = digest
return actor
def actor(request: Request) -> dict[str, Any]:
found = getattr(request.state, "actor", None)
return found if found is not None else _authenticate(request)
def basic_credentials(request: Request) -> tuple[str, str]:
auth = request.headers.get("authorization", "")
parts = auth.split(" ", 1)
if len(parts) != 2 or parts[0].lower() != "basic":
raise APIError(401, "unauthorized", "Unauthorized")
try:
raw = base64.b64decode(parts[1], validate=True).decode("utf-8")
username, password = raw.split(":", 1)
except (ValueError, UnicodeError, binascii.Error):
raise APIError(401, "unauthorized", "Unauthorized")
if not USERNAME_RE.fullmatch(username) or not password:
raise APIError(401, "unauthorized", "Unauthorized")
return username, password
def cursor_encode(payload: dict[str, str]) -> str:
return base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode("ascii")).decode("ascii").rstrip("=")
def cursor_decode(raw: str | None, *, kind: str, scope_key: str, scope_id: str) -> tuple[datetime, uuid.UUID] | None:
if raw is None:
return None
try:
if not raw or not re.fullmatch(r"[A-Za-z0-9_-]+", raw) or len(raw) > 1500:
raise ValueError("bad cursor")
value = json.loads(base64.urlsafe_b64decode(raw + ("=" * (-len(raw) % 4))))
if not isinstance(value, dict) or set(value) != {"kind", scope_key, "created_at", "id"}:
raise ValueError("bad cursor fields")
if value["kind"] != kind or value[scope_key] != scope_id:
raise ValueError("wrong cursor context")
stamp = value["created_at"]
if not isinstance(stamp, str) or not stamp.endswith("Z"):
raise ValueError("invalid timestamp")
when = datetime.fromisoformat(stamp.replace("Z", "+00:00"))
if when.utcoffset() != timedelta(0):
raise ValueError("not UTC")
return when, uuid.UUID(value["id"])
except (ValueError, TypeError, KeyError, UnicodeError, binascii.Error):
raise APIError(400, "invalid_request", "Invalid cursor")
def cursor_next(kind: str, scope_key: str, scope_id: str, row: dict[str, Any]) -> str:
return cursor_encode({"kind": kind, scope_key: scope_id, "created_at": iso(row["created_at"]), "id": str(row["id"])})
def read_chat(conn: psycopg.Connection, cid: uuid.UUID, uid: uuid.UUID) -> dict[str, Any]:
row = conn.execute("""
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT cm2.user_id FROM chat_members cm2 WHERE cm2.chat_id=c.id ORDER BY cm2.position) AS member_ids
FROM chats c JOIN chat_members mine ON mine.chat_id=c.id
WHERE c.id=%s AND mine.user_id=%s
""", (cid, uid)).fetchone()
if row is None:
raise APIError(404, "not_found", "Object not found")
return row
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
def ready(request: Request):
with request.app.state.pool.connection() as conn:
conn.execute("SELECT 1")
request.app.state.sessions.ping()
return {"status": "ok"}
@app.post("/api/v1/users", status_code=201)
def create_user(body: CreateUser, request: Request):
new_id = uuid.uuid4()
hashed = ph.hash(body.password)
try:
with request.app.state.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
""", (new_id, body.username, body.display_name.encode("utf-8"), hashed)).fetchone()
except UniqueViolation:
raise APIError(409, "conflict", "Username already exists")
return user_public(row)
@app.post("/api/v1/auth/sessions", status_code=201)
def create_session(request: Request):
# Contract: this endpoint uses Basic credentials only, never a JSON body.
if request.headers.get("content-length") not in (None, "", "0") or request.headers.get("transfer-encoding"):
raise APIError(400, "invalid_request", "Request body is not supported")
username, password = basic_credentials(request)
with request.app.state.pool.connection() as conn:
row = conn.execute("SELECT id, username, display_name, created_at, password_hash FROM users WHERE username=%s", (username,)).fetchone()
try:
is_valid = ph.verify(row["password_hash"] if row else DUMMY_HASH, password)
except (VerificationError, InvalidHashError):
is_valid = False
if row is None or not is_valid:
raise APIError(401, "unauthorized", "Unauthorized")
token = secrets.token_urlsafe(32) # 32 cryptographically random bytes (256 bits).
digest = hashlib.sha256(token.encode("ascii")).hexdigest()
ttl = request.app.state.session_ttl
request.app.state.sessions.set("session:" + digest, str(row["id"]), ex=ttl)
expiry = datetime.now(timezone.utc) + timedelta(seconds=ttl)
return {"token": token, "token_type": "Bearer", "expires_at": iso(expiry), "user": user_public(row)}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def logout(request: Request):
actor(request)
request.app.state.sessions.delete("session:" + request.state.session_digest)
return Response(status_code=204)
@app.get("/api/v1/users/me")
def users_me(request: Request):
return actor(request)
@app.post("/api/v1/chats", status_code=201)
def create_chat(request: Request, body: CreateChat):
uid = uuid.UUID(actor(request)["id"])
members = [valid_uuid(raw, "member_id") for raw in body.member_ids]
if len(set(members)) != len(members) or uid not in members:
raise APIError(400, "invalid_request", "Invalid chat members")
cid = uuid.uuid4()
with request.app.state.pool.connection() as conn:
with conn.transaction():
existing = conn.execute("SELECT id FROM users WHERE id=ANY(%s)", (members,)).fetchall()
if len(existing) != len(members):
raise APIError(400, "invalid_request", "Unknown member")
row = conn.execute("INSERT INTO chats(id, title) VALUES (%s,%s) RETURNING id,title,created_at", (cid, body.title.encode("utf-8"))).fetchone()
for index, member in enumerate(members):
conn.execute("INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,%s)", (cid, member, index))
return chat_public({**row, "member_ids": members})
@app.get("/api/v1/chats")
def list_chats(request: Request, limit: str | None = Query(default=None), cursor: str | None = Query(default=None)):
uid = uuid.UUID(actor(request)["id"])
size = limit_value(limit)
key = cursor_decode(cursor, kind="chats", scope_key="user_id", scope_id=str(uid))
with request.app.state.pool.connection() as conn:
if key:
match = conn.execute("""
SELECT 1 FROM chats c JOIN chat_members cm ON c.id=cm.chat_id
WHERE cm.user_id=%s AND c.id=%s AND c.created_at=%s
""", (uid, key[1], key[0])).fetchone()
if match is None:
raise APIError(400, "invalid_request", "Invalid cursor")
query = """
SELECT c.id,c.title,c.created_at,
ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.position) AS member_ids
FROM chats c JOIN chat_members cm ON cm.chat_id=c.id
WHERE cm.user_id=%s
"""
params: list[Any] = [uid]
if key:
query += " AND (c.created_at,c.id)>(%s,%s)"
params.extend(key)
query += " ORDER BY c.created_at,c.id LIMIT %s"
rows = conn.execute(query, [*params, size+1]).fetchall()
page = rows[:size]
return {"items": [chat_public(r) for r in page], "next_cursor": cursor_next("chats", "user_id", str(uid), page[-1]) if len(rows)>size else None}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, request: Request):
uid = uuid.UUID(actor(request)["id"])
with request.app.state.pool.connection() as conn:
row = read_chat(conn, valid_uuid(chat_id, "chat_id"), uid)
return chat_public(row)
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def create_message(chat_id: str, request: Request, body: CreateMessage):
uid = uuid.UUID(actor(request)["id"])
cid = valid_uuid(chat_id, "chat_id")
with request.app.state.pool.connection() as conn:
read_chat(conn, cid, uid)
row = conn.execute("""
INSERT INTO messages(id,chat_id,sender_id,text)
VALUES (%s,%s,%s,%s) RETURNING id,chat_id,sender_id,text,created_at
""", (uuid.uuid4(), cid, uid, body.text.encode("utf-8"))).fetchone()
return message_public(row)
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(chat_id: str, request: Request, limit: str | None = Query(default=None), cursor: str | None = Query(default=None)):
uid = uuid.UUID(actor(request)["id"])
cid = valid_uuid(chat_id, "chat_id")
size = limit_value(limit)
key = cursor_decode(cursor, kind="messages", scope_key="chat_id", scope_id=str(cid))
with request.app.state.pool.connection() as conn:
read_chat(conn, cid, uid)
if key:
found = conn.execute("SELECT 1 FROM messages WHERE chat_id=%s AND id=%s AND created_at=%s", (cid, key[1], key[0])).fetchone()
if not found:
raise APIError(400, "invalid_request", "Invalid cursor")
query = """
SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=%s
"""
params: list[Any] = [cid]
if key:
query += " AND (created_at,id)>(%s,%s)"
params.extend(key)
query += " ORDER BY created_at,id LIMIT %s"
rows = conn.execute(query, [*params, size+1]).fetchall()
page = rows[:size]
return {"items": [message_public(r) for r in page], "next_cursor": cursor_next("messages", "chat_id", str(cid), page[-1]) if len(rows)>size else None}
+29
View File
@@ -0,0 +1,29 @@
"""Versioned transactional SQL migration runner, safe to rerun."""
import os
from pathlib import Path
import psycopg
def main():
folder = Path(__file__).resolve().parent.parent / 'db' / 'migrations'
files = sorted(folder.glob('*.sql'))
if not files:
raise RuntimeError('no migrations')
with psycopg.connect(os.environ['DATABASE_URL'], connect_timeout=5) as conn:
with conn.transaction():
# Serialize migration runners and all schema changes in the transaction.
conn.execute('SELECT pg_advisory_xact_lock(12803802)')
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())')
applied = {r[0] for r in conn.execute('SELECT version FROM schema_migrations')}
if any(name not in {f.name for f in files} for name in applied):
raise RuntimeError('database contains unknown migration version')
for file in files:
if file.name in applied:
continue
conn.execute(file.read_text(encoding='utf-8'))
conn.execute('INSERT INTO schema_migrations(version) VALUES (%s)', (file.name,))
print('Applied migration', file.name)
print('Migrations up to date')
if __name__ == '__main__':
main()
+65
View File
@@ -0,0 +1,65 @@
services:
postgres:
image: postgres:16.10-bookworm
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB:?set in .env}
POSTGRES_USER: ${POSTGRES_USER:?set in .env}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set in .env}
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\""]
interval: 5s
timeout: 3s
retries: 20
networks: [backend]
redis:
image: redis:7.4.5-alpine
restart: unless-stopped
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "always", "--save", "60", "1"]
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 20
networks: [backend]
migrate:
build: .
command: ["python", "-m", "app.migrate"]
environment:
DATABASE_URL: postgresql://${POSTGRES_USER:?}:${POSTGRES_PASSWORD:?}@postgres:5432/${POSTGRES_DB:?}
depends_on:
postgres:
condition: service_healthy
restart: "no"
networks: [backend]
api:
build: .
restart: unless-stopped
environment:
DATABASE_URL: postgresql://${POSTGRES_USER:?}:${POSTGRES_PASSWORD:?}@postgres:5432/${POSTGRES_DB:?}
REDIS_URL: redis://redis:6379/0
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
DB_POOL_MAX: ${DB_POOL_MAX:-8}
depends_on:
migrate:
condition: service_completed_successfully
redis:
condition: service_healthy
ports:
- "127.0.0.1:8080:8080"
networks: [backend]
volumes:
postgres_data:
redis_data:
networks:
backend:
driver: bridge
+31
View File
@@ -0,0 +1,31 @@
CREATE TABLE users (
id uuid PRIMARY KEY,
username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name varchar(100) NOT NULL CHECK (length(btrim(display_name)) > 0),
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title varchar(100) NOT NULL CHECK (length(btrim(title)) > 0),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
position smallint NOT NULL CHECK (position >= 0),
PRIMARY KEY (chat_id,user_id),
UNIQUE (chat_id,position)
);
CREATE INDEX idx_chat_members_user ON chat_members (user_id,chat_id);
CREATE INDEX idx_chats_page ON chats (created_at,id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE RESTRICT,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
CONSTRAINT message_sender_is_member FOREIGN KEY (chat_id,sender_id)
REFERENCES chat_members(chat_id,user_id) ON DELETE RESTRICT,
text varchar(4000) NOT NULL CHECK (length(btrim(text)) > 0),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX idx_messages_chat_history ON messages (chat_id,created_at,id);
+17
View File
@@ -0,0 +1,17 @@
-- PostgreSQL text/varchar reject the NUL character, but the public API accepts
-- arbitrary valid UTF-8 code points in display_name, title and message text.
-- Store exact UTF-8 bytes in bytea while enforcing code-point limits at API.
-- Existing rows are converted losslessly; safe with persistent lab2 volumes.
ALTER TABLE users DROP CONSTRAINT users_display_name_check;
ALTER TABLE chats DROP CONSTRAINT chats_title_check;
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE users ALTER COLUMN display_name TYPE bytea USING convert_to(display_name, 'UTF8');
ALTER TABLE chats ALTER COLUMN title TYPE bytea USING convert_to(title, 'UTF8');
ALTER TABLE messages ALTER COLUMN text TYPE bytea USING convert_to(text, 'UTF8');
-- A valid UTF-8 code point occupies at most four bytes.
-- Pydantic enforces 1..100/4000 code points and no whitespace-only strings.
ALTER TABLE users ADD CONSTRAINT users_display_name_octets CHECK (octet_length(display_name) BETWEEN 1 AND 400);
ALTER TABLE chats ADD CONSTRAINT chats_title_octets CHECK (octet_length(title) BETWEEN 1 AND 400);
ALTER TABLE messages ADD CONSTRAINT messages_text_octets CHECK (octet_length(text) BETWEEN 1 AND 16000);
+6
View File
@@ -0,0 +1,6 @@
fastapi==0.128.2
uvicorn==0.48.0
pydantic==2.13.4
psycopg[binary,pool]==3.2.10
redis==6.4.0
argon2-cffi==25.1.0
+41
View File
@@ -0,0 +1,41 @@
"""Create synthetic 10k-message history and print query plan. Execute inside api container.
Only generates isolated synthetic UUID user/chat; never truncates real data.
"""
import os
import uuid
import psycopg
def main():
uid, cid = uuid.uuid4(), uuid.uuid4()
with psycopg.connect(os.environ['DATABASE_URL']) as conn:
conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)",
(uid, 'ex_' + uuid.uuid4().hex[:12], b'EXPLAIN fixture', 'synthetic-not-for-login'))
conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s)", (cid,b'EXPLAIN synthetic history'))
conn.execute("INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,0)", (cid,uid))
conn.execute("""
INSERT INTO messages(id,chat_id,sender_id,text,created_at)
SELECT gen_random_uuid(), %s, %s, convert_to('synthetic-' || n::text, 'UTF8'),
clock_timestamp() + (n * interval '1 microsecond')
FROM generate_series(1, 10000) AS n
""", (cid,uid))
middle = conn.execute("""
SELECT created_at,id FROM messages WHERE chat_id=%s
ORDER BY created_at,id OFFSET 5000 LIMIT 1
""", (cid,)).fetchone()
conn.execute('ANALYZE messages')
count = conn.execute('SELECT count(*) FROM messages WHERE chat_id=%s', (cid,)).fetchone()[0]
assert count==10000
plan = conn.execute("""
EXPLAIN (ANALYZE,BUFFERS)
SELECT id,chat_id,sender_id,text,created_at
FROM messages WHERE chat_id=%s AND (created_at,id)>(%s,%s)
ORDER BY created_at,id LIMIT 50
""", (cid,*middle)).fetchall()
print('Fixture chat_id:', cid, '; history size:', count)
print('\n'.join(row[0] for row in plan))
print('Index intended: idx_messages_chat_history (chat_id,created_at,id)')
print('Fixture retained to reproduce measurements; clean only in isolated test volume.')
if __name__ == '__main__':
main()
+35
View File
@@ -0,0 +1,35 @@
@echo off
setlocal EnableExtensions
cd /d "%~dp0.."
if errorlevel 1 goto :fail
echo [restart] Stopping API...
docker compose --env-file .env stop api
if errorlevel 1 goto :fail
echo [restart] Stopping Redis...
docker compose --env-file .env stop redis
if errorlevel 1 goto :fail
echo [restart] Stopping PostgreSQL...
docker compose --env-file .env stop postgres
if errorlevel 1 goto :fail
echo [restart] Starting storage services and waiting for healthchecks...
docker compose --env-file .env up -d --no-deps --wait --wait-timeout 45 postgres redis
if errorlevel 1 goto :fail
echo [restart] Starting API...
docker compose --env-file .env up -d --no-deps api
if errorlevel 1 goto :fail
echo [restart] Waiting for API readiness (PostgreSQL + Redis)...
powershell.exe -NoProfile -NonInteractive -Command "$deadline=(Get-Date).AddSeconds(30); while((Get-Date) -lt $deadline) { try { $r=Invoke-WebRequest -UseBasicParsing -Uri 'http://127.0.0.1:8080/health/ready' -TimeoutSec 2 -ErrorAction Stop; if($r.StatusCode -eq 200) { exit 0 } } catch {} ; Start-Sleep -Seconds 1 }; exit 1"
if errorlevel 1 goto :fail
echo [restart] OK: all runtime services restarted; API ready.
exit /b 0
:fail
echo [restart] FAILED. Inspect docker compose ps and logs. 1>&2
exit /b 1
+37
View File
@@ -0,0 +1,37 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
compose() {
docker compose --env-file .env "$@"
}
printf '%s\n' '[restart] Stopping API...'
compose stop api
printf '%s\n' '[restart] Stopping Redis...'
compose stop redis
printf '%s\n' '[restart] Stopping PostgreSQL...'
compose stop postgres
printf '%s\n' '[restart] Starting PostgreSQL and Redis; waiting for healthchecks...'
compose up -d --no-deps --wait --wait-timeout 60 postgres redis
printf '%s\n' '[restart] Starting API...'
compose up -d --no-deps api
printf '%s\n' '[restart] Waiting for API readiness...'
i=0
while [ "$i" -lt 60 ]; do
if compose exec -T api python -c 'import urllib.request; urllib.request.urlopen("http://127.0.0.1:8080/health/ready", timeout=2)' >/dev/null 2>&1; then
printf '%s\n' '[restart] OK: all runtime services restarted; API ready.'
exit 0
fi
i=$((i + 1))
sleep 1
done
printf '%s\n' '[restart] FAILED: API did not become ready within 60 seconds; inspect docker compose ps/logs.' >&2
exit 1
+31
View File
@@ -0,0 +1,31 @@
"""Show PostgreSQL rollback after partial composite operation, without modifying API code.
Same two-table transaction pattern used by POST /chats, inject a FK failure midway.
"""
import os
import uuid
import psycopg
from psycopg.errors import ForeignKeyViolation
def main():
with psycopg.connect(os.environ['DATABASE_URL']) as conn:
uid = conn.execute('SELECT id FROM users LIMIT 1').fetchone()
if uid is None:
print('Create a user with make test first')
raise SystemExit(1)
cid = uuid.uuid4()
try:
with conn.transaction():
conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (cid, b'Rollback test'))
conn.execute('INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,0)', (cid, uid[0]))
conn.execute('INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,1)', (cid, uuid.uuid4()))
raise AssertionError('FK should have failed')
except ForeignKeyViolation:
pass
# Connection still usable because transaction block rolled back.
orphan = conn.execute('SELECT 1 FROM chats WHERE id=%s', (cid,)).fetchone()
assert orphan is None, 'partial chat remained after rollback'
print('PASS: composite chat insert was fully rolled back after FK failure')
if __name__ == '__main__':
main()
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""Grade-4 Redis/Postgres failure injection for isolated local Compose environment.
Requires Docker permissions; never uses 'down -v'. Never prints tokens.
"""
import subprocess
import time
from client import Client, Failure, check, run
def compose(*args):
outcome = subprocess.run(['docker','compose','--env-file','.env',*args],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
check(outcome.returncode==0, 'docker compose action failed; inspect locally')
def wait_ready(c, status):
until = time.monotonic()+60
while time.monotonic()<until:
try:
c.call('GET','/health/ready',status)
return
except Failure:
time.sleep(0.5)
raise Failure('readiness did not reach '+str(status))
def main():
c=Client(timeout=10)
alice = c.user('dependency')
for service in ('redis','postgres'):
try:
compose('stop',service)
wait_ready(c,503)
c.call('GET','/api/v1/users/me',503,actor=alice)
finally:
compose('start',service)
wait_ready(c,200)
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
print('PASS:', service, 'outage returned 503; recovered without losing session')
if __name__ == '__main__':
run(main)
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env python3
"""Requires a separate short-TTL run (SESSION_TTL_SECONDS=2); checks expiry automatically."""
import time
from client import Client, run
def main():
c = Client()
alice = c.user('expiry')
time.sleep(3.1)
c.call('GET','/api/v1/users/me',401,actor=alice)
print('PASS: short-lived Bearer session expires and is rejected')
if __name__ == '__main__':
run(main)
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Additional grade-4 tests: validation, authentication and username race.
Run against an isolated running lab2 stack. Uses unique test usernames.
"""
import base64
from concurrent.futures import ThreadPoolExecutor
import time
import uuid
from client import Client, check, run
def main():
c = Client()
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id']
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic NOT-BASE64'})
incorrect = base64.b64encode((alice['registration']['username'] + ':wrong-password').encode()).decode()
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + incorrect})
c.call('POST','/api/v1/users',400,body={**alice['registration'],'admin':True})
c.call('POST','/api/v1/users',400,body={'username':'xy','display_name':'Valid','password':'long-password-123'})
c.call('POST','/api/v1/users',400,body={'username':'anothername','display_name':'Valid','password':'short'})
c.call('POST','/api/v1/users',400,body={'username':'blankpass_' + uuid.uuid4().hex[:8], 'display_name':'Valid','password':' '*12})
credentials = base64.b64encode((alice['registration']['username']+':'+alice['registration']['password']).encode('utf-8')).decode('ascii')
c.call('POST','/api/v1/auth/sessions',400,headers={'Authorization':'Basic '+credentials},body={'unexpected':True})
c.call('POST','/api/v1/auth/sessions',400,headers={'Authorization':'Basic '+credentials},body={})
c.call('POST','/api/v1/chats',400,actor=alice,body={'title':'Too many members', 'member_ids':[alice['id']]+[str(uuid.uuid4()) for _ in range(100)]})
c.call('POST','/api/v1/chats',400,actor=alice,body={'title':'bad','member_ids':[alice['id'],alice['id']]})
c.call('POST','/api/v1/chats',400,actor=alice,body={'title':'bad','member_ids':[alice['id'],str(uuid.uuid4())]})
c.call('POST',path+'/messages',400,actor=alice,body={'text':' '})
# PostgreSQL text/varchar reject NUL. Public API does not: verify exact
# round-trip through bytea storage for all three user-controlled fields.
special = 'A\x00Б'
nul_user = c.call('POST','/api/v1/users',201,body={'username':'nul_' + uuid.uuid4().hex[:12], 'display_name':special, 'password':'Strong-password-123'},schema='User')['json']
check(nul_user['display_name']==special,'display_name U+0000 round-trip failed')
nul_chat = c.call('POST','/api/v1/chats',201,actor=alice,body={'title':special,'member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
check(nul_chat['title']==special,'chat title U+0000 round-trip failed')
fetched_chat = c.call('GET','/api/v1/chats/'+nul_chat['id'],actor=bob,schema='Chat')['json']
check(fetched_chat['title']==special,'chat GET title U+0000 round-trip failed')
special_message = c.call('POST',path+'/messages',201,actor=alice,body={'text':special},schema='Message')['json']
check(special_message['text']==special,'message U+0000 write lost data')
items = c.call('GET',path+'/messages',actor=bob,schema='MessagePage')['json']['items']
check(any(m['id']==special_message['id'] and m['text']==special for m in items),'message GET lost U+0000')
max_message = 'Ж'*3999 + '\x00'
posted_max = c.call('POST',path+'/messages',201,actor=alice,body={'text':max_message},schema='Message')['json']
check(posted_max['text']==max_message,'max-length UTF8/NUL failed')
c.call('POST',path+'/messages',404,actor=eve,body={'text':'bad outsider'})
c.call('GET',path+'/messages?limit=0',400,actor=alice)
c.call('GET',path+'/messages?limit=101',400,actor=alice)
c.call('GET',path+'/messages?cursor=notvalid',400,actor=alice)
c.call('POST','/api/v1/users',415,raw=b'{}',headers={'Content-Type':'text/plain'})
c.call('POST','/api/v1/users',400,raw=b'{"bad json":',headers={'Content-Type':'application/json'})
token_alice = alice['token']
c.call('GET','/api/v1/users/me',actor=alice,headers={'X-User-Id':eve['id']},schema='User')
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Bearer '+token_alice})
username = 'race_' + uuid.uuid4().hex[:12]
payload = {'username':username,'display_name':'Race','password':'Race-password-123456'}
def worker(_):
return Client().call('POST','/api/v1/users',[201,409],body=payload)['status']
with ThreadPoolExecutor(max_workers=10) as executor:
statuses = list(executor.map(worker, range(10)))
check(statuses.count(201)==1 and statuses.count(409)==9,'concurrent username race was not serialized by UNIQUE')
print('PASS: grade4 API negatives, login body, Unicode NUL round-trip, max members and username race')
if __name__ == '__main__':
run(main)
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
"""Optional operator test for Redis session corruption on an isolated lab stack.
No other users' keys are modified. Run only against own Docker Compose setup.
"""
import hashlib
import subprocess
from client import Client, check, run
def main():
c = Client()
user = c.user('cachecorrupt')
digest = hashlib.sha256(user['token'].encode('ascii')).hexdigest()
key = 'session:' + digest
cmd = ['docker','compose','--env-file','.env','exec','-T','redis','redis-cli']
proc = subprocess.run(cmd + ['SET',key,'null','EX','30'], text=True, capture_output=True)
check(proc.returncode == 0 and 'OK' in proc.stdout, 'could not inject synthetic corrupt Redis session')
c.call('GET','/api/v1/users/me',401,actor=user)
proc = subprocess.run(cmd + ['EXISTS', key], text=True, capture_output=True)
check(proc.returncode == 0 and proc.stdout.strip()=='0', 'corrupt session key was not removed')
print('PASS: malformed Redis session value fails closed with 401 and is removed')
if __name__=='__main__':
run(main)