From ac54d4cfde5fa2876fdfedf55fd7d5840c33cdac Mon Sep 17 00:00:00 2001 From: Conloty <149334964+Conloty@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:52:21 +0300 Subject: [PATCH 1/2] lab2: PostgreSQL, sessions, compose, evidence tooling. --- .gitattributes | 5 + .gitignore | 6 + Dockerfile | 11 + REPORT.md | 101 ++++++++-- compose.yaml | 34 ++++ scripts/collect-evidence.sh | 157 +++++++++++++++ scripts/restart.cmd | 6 + scripts/restart.sh | 7 + scripts/setup-secrets.sh | 11 + src/app/__init__.py | 0 src/app/main.py | 378 +++++++++++++++++++++++++++++++++++ src/app/migrate.py | 25 +++ src/migrations/001_init.sql | 39 ++++ src/requirements.txt | 4 + student-tests/lab2_checks.py | 231 +++++++++++++++++++++ 15 files changed, 1001 insertions(+), 14 deletions(-) create mode 100644 .gitattributes create mode 100644 Dockerfile create mode 100644 compose.yaml create mode 100644 scripts/collect-evidence.sh create mode 100644 scripts/restart.cmd create mode 100644 scripts/restart.sh create mode 100644 scripts/setup-secrets.sh create mode 100644 src/app/__init__.py create mode 100644 src/app/main.py create mode 100644 src/app/migrate.py create mode 100644 src/migrations/001_init.sql create mode 100644 src/requirements.txt create mode 100644 student-tests/lab2_checks.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..9cb982cd --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +*.sh text eol=lf +Dockerfile text eol=lf +*.sql text eol=lf +*.py text eol=lf +*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore index b5a71896..a4d6b444 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,9 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. + +# lab2 +secrets/ +.env +.venv/ +__pycache__/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..9c2d536e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.12.7-slim-bookworm +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 +WORKDIR /app +COPY src/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +COPY src/ . +RUN useradd -r -u 10001 appuser +USER appuser +EXPOSE 8080 +HEALTHCHECK --interval=5s --timeout=3s --retries=10 CMD python -c "import urllib.request as u;u.urlopen('http://127.0.0.1:8080/health/live',timeout=2)" +CMD ["uvicorn","app.main:app","--host","0.0.0.0","--port","8080"] diff --git a/REPORT.md b/REPORT.md index e42f2b05..900b5272 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,110 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Корнилов Михаил Андреевич, БПИ2304 +- Целевая оценка: 3. +- Commit/PR: TODO после публикации (commit, на котором собраны доказательства, указан в `evidence/01-env.txt`) +- Использованные источники, библиотеки и помощь ИИ: Библиотеки: starlette, uvicorn, psycopg 3 + psycopg_pool, argon2-cffi. Каталог `tests/` и `contracts/` курса не менялись. При подготовке использовалась помощь Claude ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Стенд проверялся на Windows + Docker Desktop (WSL2): Docker 28.0.4, Compose v2.34.0, Python 3.11.5 для тестов, хост 16 CPU / 8 ГБ. Образы: `postgres:16.4-alpine`, `python:3.12.7-slim-bookworm` (версии закреплены). + +Команды выполняются в Git Bash (на Linux/macOS — в любом sh) из корня репозитория: + +```sh +sh scripts/setup-secrets.sh # создаёт secrets/pg_password и secrets/database_url (в .gitignore, значения не печатаются) +docker compose up -d --build # миграции применяются при старте API +curl http://localhost:8080/health/ready # ждём {"status":"ok"} +python tests/smoke.py --base-url http://localhost:8080 # = make test +python tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080 + # на Linux/macOS: --action-script scripts/restart.sh (= make test-persistence) +sh scripts/collect-evidence.sh # все проверки ниже и сохранение в evidence/ (--fresh сначала удаляет данные) +docker compose stop # безопасная остановка: контейнеры остановлены, данные сохранены +docker compose down -v # ОСОЗНАННОЕ удаление учебных данных (том pgdata) +``` + +Действия оператора: только `setup-secrets.sh` (создать секреты). `.env` не обязателен: у переменных есть значения по умолчанию в `compose.yaml`; при желании `cp .env.example .env`. Порт API опубликован только на `127.0.0.1:8080`, PostgreSQL наружу не опубликован. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Клиент → API (Starlette/uvicorn, непривилегированный пользователь в контейнере) → PostgreSQL 16 (именованный том `pgdata`). Источник истины — PostgreSQL, сессии тоже хранятся там, поэтому они переживают рестарт API и БД. + +- Таблицы: `users`, `chats`, `chat_members`, `messages`, `sessions`, `schema_migrations`; PK/FK, `UNIQUE(username)`, CHECK на длины и формат (схема — `evidence/05-db-schema.txt`). +- Миграции: `src/migrations/*.sql`, применяются при старте API по порядку под advisory lock, версии пишутся в `schema_migrations`; повторный запуск ничего не дублирует. +- Транзакционная граница: создание чата (чат + участники) выполняется в одной транзакции. +- Пароли: Argon2id (argon2-cffi, параметры по умолчанию). Токен: `secrets.token_urlsafe(32)` (256 бит); в БД хранится только sha256 токена (32 байта). +- Basic принимается только на `POST /auth/sessions`; остальные endpoint — только Bearer. `X-User-Id` игнорируется. Logout ставит `revoked_at`; срок жизни — `SESSION_TTL_SECONDS` (по умолчанию 3600). +- История сообщений: keyset по `(created_at, id)`, индекс `messages(chat_id, created_at, id)`, cursor привязан к чату. +- Готовность: `/health/live` не зависит от БД; `/health/ready` и бизнес-endpoint при недоступной БД отвечают 503 в общем формате ошибок. Пул соединений (`min 2`, `max DB_POOL_MAX=10`, таймаут получения соединения 2 с) восстанавливается сам. + +**Из lab1 перенесено:** все endpoint (`/users`, `/users/me`, `/chats`, `/chats/{id}`, сообщения), формат ошибок и `X-Request-Id`, валидация полей, keyset-пагинация, коды 400/401/404/413/415. Хранилище in-memory заменено PostgreSQL. +**Изменено по объявленным переходам:** при регистрации передаётся `password`; вместо `X-User-Id` — сессии (`POST /auth/sessions`, `DELETE /auth/sessions/current`, Bearer). Неверный UUID в пути везде даёт 400, как в lab1. + +**Соответствие `.env.example`:** + +| Переменная | Статус | +| --- | --- | +| `SESSION_TTL_SECONDS` | используется (compose передаёт в API) | +| `DATABASE_URL_FILE` | используется (`/run/secrets/database_url`, Docker secret) | +| `APP_ENV` | передаётся в контейнер, приложением не читается | +| `APP_HOST`, `APP_PORT` | не читаются; адрес и порт заданы в `CMD` Dockerfile (`0.0.0.0:8080`), наружу порт публикуется на `127.0.0.1` | +| `SESSION_STORE=postgres` | только маркер: сессии всегда в PostgreSQL | +| `CACHE_URL_FILE` | не используется (Redis/Valkey нужен на 4) | +| `DB_POOL_MAX` | читается приложением (по умолчанию 10), в `.env.example` отсутствует | ## Доказательства критериев +Все файлы лежат в `evidence/`; они собраны одним запуском `sh scripts/collect-evidence.sh`, токены и пароли в них не печатаются. + | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +| Публичный smoke | `python tests/smoke.py` | PASS; `scripts/check_contract.py` — PASS | `02-smoke.txt` | +| PostgreSQL, PK/FK, уникальный username | `\d` по всем таблицам | `users_pkey`, `UNIQUE(username)`, FK `chat_members`/`messages`/`sessions`, индексы истории | `05-db-schema.txt` | +| Версионируемые миграции, повтор без дублей | рестарт API + 2 явных вызова `migrate.run` | одна запись `001_init.sql`, число users/messages не изменилось | `06-migrations.txt` | +| Пароль хранится как KDF-хэш | `select left(password_hash,10)` | 10 из 10 хэшей начинаются с `$argon2id$` | `05-db-schema.txt` | +| Токен не хранится в открытом виде | `select length(token_hash)` | 10 из 10 — 32 байта (sha256) | `05-db-schema.txt` | +| Basic только на входе, Bearer на остальном; `X-User-Id` игнорируется | собственные проверки | Basic на `/users/me` → 401; один `X-User-Id` → 401; при Bearer + чужом `X-User-Id` владелец определяется токеном | `03-student-checks.txt` | +| Вход неотличим при неверном пароле и неизвестном пользователе | собственные проверки | оба случая 401 с одинаковыми code/message/`WWW-Authenticate` | `03-student-checks.txt` | +| Logout и срок жизни сессии | logout; TTL=2 с | logout 204, повтор → 401, токен после logout → 401; при TTL=2 токен рабочий сразу и недействителен через 3,5 с | `03-student-checks.txt`, `07-ttl.txt` | +| Гонка регистрации одного username | 10 параллельных запросов | ровно один 201, остальные 409 | `03-student-checks.txt` | +| Атомарное создание чата | чат с несуществующим участником | 400, число чатов пользователя не изменилось | `03-student-checks.txt` | +| Доступ только участникам | запросы постороннего | 404 на чат, историю и отправку; неверный UUID → 400 | `03-student-checks.txt` | +| Пагинация | `limit=2`, cursor | 6 сообщений без повторов; cursor другого чата, `limit=0/101/abc/+5`, повтор параметра → 400 | `03-student-checks.txt` | +| Сохранность при рестарте API и БД | `tests/resilience.py --mode persistence`, hook `scripts/restart.cmd` | PASS; `StartedAt` обоих контейнеров изменился, `RestartCount=0`; после рестарта в БД users=10, chats=4, messages=9, sessions=10 | `04-persistence.txt` | +| Hook действительно перезапускает процессы | `docker inspect … StartedAt` до/после | postgres 18:07:23 → 18:07:42, api 18:07:27 → 18:07:43 (UTC) | `04-persistence.txt` | +| Compose: именованный том, версии образов, готовность | `docker compose config/images/ps` | том `mtusi2026lab2_pgdata`, образы закреплены, оба сервиса `healthy` | `01-env.txt`, `05-db-schema.txt` | +| Секреты и volumes вне Git | `git check-ignore`, `git ls-files` | `secrets/` и `.env` игнорируются, отслеживаемых секретов нет | `09-git-hygiene.txt` | -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +Примечание к проверке hook: `tests/resilience.py` подтверждает сохранность данных и сессии, а какие процессы перезапущены, показывают значения `StartedAt` выше (перезапущены оба контейнера: сначала `postgres`, после `pg_isready` — `api`). ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Нагрузочные измерения (RPS, p50/p95/p99) на уровне 3 не проводились. Проверены отказы: | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Рестарт `postgres` и `api` (`scripts/restart.cmd`) | данные и сессия сохраняются | PASS; оба контейнера перезапущены | ≈4 с до `/health/ready`; потерь нет | +| Рестарт только `api` | миграции не дублируются | одна запись `001_init.sql`, users и messages без изменений | готов сразу после старта; потерь нет | +| `docker compose stop postgres` при работающем API | `live` 200, `ready` и бизнес-endpoint 503 без падения API | `live` 200; `ready` и `/users/me` — 503 в общем формате (с `request_id`) | после `start postgres` `ready` вернулся ≈ через 1 с без рестарта API; потерь нет | +| `SESSION_TTL_SECONDS=2` | токен действует сразу и истекает | 200, затем 401 через 3,5 с | возврат к TTL 3600 пересозданием `api` | + +Версии, лимиты и загрузка на момент прогона — `evidence/01-env.txt`; значения времени восстановления — из прогона, лежащего в `evidence/`, на другой машине они могут отличаться на секунды. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Уровень 4 не реализован: нет Redis/Valkey, плана `EXPLAIN` на большом объёме и тестов отказа кэша. Нагрузочный эксперимент уровня 5 не выполнялся. +- Одна БД без репликации и бэкапов, один Docker-host: при потере тома `pgdata` данные потеряны (`down -v` делает это намеренно). +- Просроченные и отозванные сессии не удаляются из `sessions` (есть индекс по `expires_at`, но очистки нет): таблица растёт без фонового удаления. +- Время сообщения берётся из `clock_timestamp()` в момент вставки; при конкурентных вставках в один чат порядок коммитов может не совпасть с порядком времени, и keyset-cursor теоретически способен пропустить запись, зафиксированную позже. Практически не воспроизводилось; строгий порядок потребовал бы счётчика/последовательности на чат. +- API при старте завершается, если БД недоступна; восстановление обеспечивает `restart: unless-stopped` и `depends_on: service_healthy`. После старта пул соединений восстанавливается сам. +- Приложение не ограничивает частоту входа (нет rate limit), защита от перебора паролей — только стоимость Argon2id. +- Реализация учебная: работоспособна и проверена, но не претендует на промышленную готовность. + +## Windows (без make) + +```sh +python tests/smoke.py --base-url http://localhost:8080 +python tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080 +``` + +Секреты: `sh scripts/setup-secrets.sh` из Git Bash (входит в Git for Windows). Docker Desktop с бэкендом WSL2. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..ea93a10b --- /dev/null +++ b/compose.yaml @@ -0,0 +1,34 @@ +services: + postgres: + image: postgres:16.4-alpine + restart: unless-stopped + environment: + POSTGRES_USER: msg + POSTGRES_DB: msg + POSTGRES_PASSWORD_FILE: /run/secrets/pg_password + secrets: [pg_password] + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U msg -d msg"] + interval: 3s + timeout: 3s + retries: 20 + api: + build: . + restart: unless-stopped + depends_on: + postgres: {condition: service_healthy} + environment: + DATABASE_URL_FILE: /run/secrets/database_url + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + APP_ENV: ${APP_ENV:-lab} + secrets: [database_url] + ports: ["127.0.0.1:8080:8080"] +secrets: + pg_password: + file: ./secrets/pg_password + database_url: + file: ./secrets/database_url +volumes: + pgdata: diff --git a/scripts/collect-evidence.sh b/scripts/collect-evidence.sh new file mode 100644 index 00000000..bb0f5d42 --- /dev/null +++ b/scripts/collect-evidence.sh @@ -0,0 +1,157 @@ +#!/bin/sh +# Собирает доказательства lab2 в evidence/*.txt. Запускать из Git Bash (Windows) или любого sh, +# когда стенд уже поднят: docker compose up -d --build. +# sh scripts/collect-evidence.sh # проверки на текущих данных +# sh scripts/collect-evidence.sh --fresh # сначала `docker compose down -v` (УДАЛЯЕТ учебные данные) и чистый старт +# Секреты и токены не печатаются. Скрипт сам перезапускает контейнеры, останавливает/запускает postgres и меняет TTL API +# на время проверки (потом возвращает 3600). Тома не удаляются, кроме режима --fresh. +set -u +export MSYS_NO_PATHCONV=1 # Git Bash: не превращать /run/... в Windows-пути +export PYTHONUTF8=1 # читаемый UTF-8 в evidence/*.txt (иначе кракозябры в Windows) +echo "Сбор доказательств: 9 шагов, 1-3 минуты. Прогресс печатается после каждого шага." +cd "$(dirname "$0")/.." || exit 1 +mkdir -p evidence +BASE="${BASE_URL:-http://localhost:8080}" +PY="" +for c in python python3 py; do + if "$c" --version >/dev/null 2>&1; then PY="$c"; break; fi +done +[ -n "$PY" ] || { echo "Не найден python (python/python3/py)"; exit 2; } +case "$(uname -s)" in + MINGW*|MSYS*|CYGWIN*) ACTION="scripts/restart.cmd" ;; + *) ACTION="scripts/restart.sh" ;; +esac + +now() { date -u +%Y-%m-%dT%H:%M:%SZ; } +sec() { date +%s; } +wait_ready() { + i=0 + until curl -fsS -m 3 "$BASE/health/ready" >/dev/null 2>&1; do + i=$((i + 1)); [ "$i" -gt 90 ] && return 1; sleep 1 + done + return 0 +} +started() { docker inspect -f '{{.Name}} StartedAt={{.State.StartedAt}} RestartCount={{.RestartCount}}' $(docker compose ps -q postgres api); } +psql_c() { docker compose exec -T postgres psql -U msg -d msg -c "$1"; } +RESULTS="" +note() { RESULTS="$RESULTS +$1"; echo "готово: $1"; } + +if [ "${1:-}" = "--fresh" ]; then + { + echo "# 00 чистый старт ($(now))" + echo "\$ docker compose down -v"; docker compose down -v + echo "\$ sh scripts/setup-secrets.sh"; sh scripts/setup-secrets.sh && echo "secrets: ok (значения не печатаются)" + t0=$(sec) + echo "\$ docker compose up -d --build"; docker compose up -d --build + if wait_ready; then echo "ready через $(( $(sec) - t0 )) с после запуска up"; else echo "НЕ ГОТОВ за 90 с"; fi + } > evidence/00-clean-start.txt 2>&1 + note "00 clean start -> evidence/00-clean-start.txt" +fi + +wait_ready || { echo "API не отвечает на $BASE/health/ready. Сначала: docker compose up -d --build"; exit 1; } + +{ + echo "# 01 окружение ($(now))" + echo "commit: $(git rev-parse HEAD 2>/dev/null || echo 'нет git')" + echo "git status:"; git status --short 2>/dev/null | head -20 + echo "\$ docker version"; docker version --format 'client={{.Client.Version}} server={{.Server.Version}} os={{.Server.Os}}/{{.Server.Arch}}' + echo "\$ docker compose version"; docker compose version + echo "python: $($PY --version 2>&1)" + echo "\$ docker compose config --quiet"; docker compose config --quiet && echo "compose config: OK" + echo "\$ docker compose images"; docker compose images + echo "\$ docker compose ps"; docker compose ps + echo "\$ docker volume ls (pgdata)"; docker volume ls | grep -i pgdata + echo "\$ docker stats --no-stream"; docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}' $(docker compose ps -q) + echo "\$ docker info (лимиты хоста)"; docker info --format 'CPUs={{.NCPU}} Mem={{.MemTotal}}' +} > evidence/01-env.txt 2>&1 +note "01 окружение -> evidence/01-env.txt" + +{ + echo "# 02 публичные проверки ($(now))" + echo "\$ python scripts/check_contract.py"; $PY scripts/check_contract.py; echo "exit code: $?" + echo "\$ python tests/smoke.py --base-url $BASE"; $PY tests/smoke.py --base-url "$BASE"; echo "exit code: $?" +} > evidence/02-smoke.txt 2>&1 +note "02 smoke -> evidence/02-smoke.txt: $(grep -c '^PASS: lab2' evidence/02-smoke.txt) PASS-строк smoke" + +{ + echo "# 03 собственные проверки ($(now))" + echo "\$ python student-tests/lab2_checks.py --base-url $BASE" + $PY student-tests/lab2_checks.py --base-url "$BASE"; echo "exit code: $?" +} > evidence/03-student-checks.txt 2>&1 +note "03 собственные -> evidence/03-student-checks.txt: $(tail -2 evidence/03-student-checks.txt | head -1)" + +{ + echo "# 04 сохранность при рестарте API и PostgreSQL ($(now))" + echo "--- до"; started; docker compose ps + echo "\$ python tests/resilience.py --mode persistence --action-script $ACTION" + $PY tests/resilience.py --mode persistence --action-script "$ACTION" --base-url "$BASE"; echo "exit code: $?" + echo "--- после (StartedAt должен измениться у обоих контейнеров)"; started; docker compose ps + echo "--- время восстановления одного рестарта (hook + ожидание /health/ready)" + t0=$(sec); sh scripts/restart.sh; if wait_ready; then echo "готов через $(( $(sec) - t0 )) с"; else echo "НЕ ГОТОВ за 90 с"; fi + echo "--- проверка сохранности данных в БД после рестарта" + psql_c "select (select count(*) from users) users, (select count(*) from chats) chats, (select count(*) from messages) messages, (select count(*) from sessions) sessions" +} > evidence/04-persistence.txt 2>&1 +note "04 persistence -> evidence/04-persistence.txt: $(grep -m1 -E '^(PASS|FAIL): persistence' evidence/04-persistence.txt || echo 'см. файл')" + +{ + echo "# 05 схема БД ($(now))" + psql_c "select * from schema_migrations" + psql_c "\\dt" + for t in users chats chat_members messages sessions; do psql_c "\\d $t"; done + echo "--- пароли хранятся как Argon2id" + psql_c "select left(password_hash, 10) as hash_prefix, count(*) from users group by 1" + echo "--- в sessions только sha256 токена (32 байта), не сам токен" + psql_c "select length(token_hash) as token_hash_bytes, count(*) from sessions group by 1" + echo "--- volume с данными PostgreSQL" + docker inspect -f '{{range .Mounts}}{{.Type}} {{.Name}} -> {{.Destination}}{{println}}{{end}}' "$(docker compose ps -q postgres)" +} > evidence/05-db-schema.txt 2>&1 +note "05 схема БД -> evidence/05-db-schema.txt" + +{ + echo "# 06 повторный запуск миграций ($(now))" + echo "--- до"; psql_c "select version from schema_migrations"; psql_c "select (select count(*) from users) users, (select count(*) from messages) messages" + echo "--- рестарт API (миграции выполняются при старте)"; docker compose restart api >/dev/null; wait_ready && echo "ready" + echo "--- ещё два явных запуска migrate.run внутри контейнера api" + for n in 1 2; do docker compose exec -T api python -c "import app.migrate as m; m.run(open('/run/secrets/database_url').read().strip()); print('migrate.run ok')"; done + echo "--- после"; psql_c "select version from schema_migrations"; psql_c "select (select count(*) from users) users, (select count(*) from messages) messages" +} > evidence/06-migrations.txt 2>&1 +note "06 миграции повторно -> evidence/06-migrations.txt" + +{ + echo "# 07 истечение сессии при SESSION_TTL_SECONDS=2 ($(now))" + echo "\$ SESSION_TTL_SECONDS=2 docker compose up -d api" + SESSION_TTL_SECONDS=2 docker compose up -d api; wait_ready && echo "ready (TTL=2)" + $PY student-tests/lab2_checks.py --base-url "$BASE" --mode ttl; echo "exit code: $?" + echo "--- возврат к TTL по умолчанию" + docker compose up -d api; wait_ready && echo "ready (TTL по умолчанию)" +} > evidence/07-ttl.txt 2>&1 +note "07 TTL -> evidence/07-ttl.txt: $(grep -m1 -E '^(PASS|FAIL): (все|[0-9])' evidence/07-ttl.txt || echo 'см. файл')" + +{ + echo "# 08 недоступность PostgreSQL ($(now))" + echo "\$ docker compose stop postgres"; docker compose stop postgres >/dev/null; sleep 2 + echo "GET /health/live -> $(curl -s -m 5 -o /dev/null -w '%{http_code}' "$BASE/health/live")" + echo "GET /health/ready -> $(curl -s -m 15 -w ' %{http_code}' "$BASE/health/ready")" + echo "GET /api/v1/users/me (анонимный токен) -> $(curl -s -m 15 -w ' %{http_code}' -H 'Authorization: Bearer anonymous' "$BASE/api/v1/users/me")" + echo "\$ docker compose start postgres"; t0=$(sec); docker compose start postgres >/dev/null + if wait_ready; then echo "ready снова через $(( $(sec) - t0 )) с (без рестарта API)"; else echo "НЕ ВОССТАНОВИЛСЯ за 90 с"; fi + docker compose ps +} > evidence/08-db-down.txt 2>&1 +note "08 БД недоступна -> evidence/08-db-down.txt" + +{ + echo "# 09 секреты и volumes вне Git ($(now))" + if git rev-parse --git-dir >/dev/null 2>&1; then + echo "\$ git check-ignore -v secrets/pg_password secrets/database_url .env"; git check-ignore -v secrets/pg_password secrets/database_url .env + echo "\$ отслеживаемые файлы, похожие на секреты:"; git ls-files | grep -E '(^|/)(secrets/|\.env$|.*\.(pem|key)$)' || echo "нет" + else + echo "каталог не является git-репозиторием: запустите проверку в клоне" + fi +} > evidence/09-git-hygiene.txt 2>&1 +note "09 git hygiene -> evidence/09-git-hygiene.txt" + +{ echo "# Сводка сбора доказательств ($(now))"; echo "$RESULTS"; echo; for f in evidence/0*.txt; do echo; echo "=================== $f"; cat "$f"; done; } > evidence/summary.txt 2>&1 +echo "$RESULTS" +echo +echo "Готово. Отправьте мне содержимое evidence/summary.txt (секретов в нём нет, но просмотрите глазами)." diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..26ea97ff --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,6 @@ +@echo off +cd /d "%~dp0.." +docker compose restart postgres >nul || exit /b 1 +docker compose exec -T postgres sh -c "i=0; until pg_isready -U msg -d msg -q; do i=$((i+1)); [ $i -gt 60 ] && exit 1; sleep 1; done" || exit /b 1 +docker compose restart api >nul +exit /b %errorlevel% diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..8eb245b1 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Перезапуск PostgreSQL и API с сохранением volumes (без down -v): сначала БД, после её готовности — API. +set -eu +cd "$(dirname "$0")/.." || exit 1 +docker compose restart postgres >/dev/null +docker compose exec -T postgres sh -c 'i=0; until pg_isready -U msg -d msg -q; do i=$((i+1)); [ "$i" -gt 60 ] && exit 1; sleep 1; done' +docker compose restart api >/dev/null diff --git a/scripts/setup-secrets.sh b/scripts/setup-secrets.sh new file mode 100644 index 00000000..b69a99c6 --- /dev/null +++ b/scripts/setup-secrets.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Создаёт локальные секреты (не коммитятся). Безопасно повторять: существующие не перезаписываются. +set -eu +mkdir -p secrets +if [ ! -f secrets/pg_password ]; then + head -c 24 /dev/urandom | base64 | tr -d '/+=\n' > secrets/pg_password +fi +if [ ! -f secrets/database_url ]; then + printf 'postgresql://msg:%s@postgres:5432/msg' "$(cat secrets/pg_password)" > secrets/database_url +fi +chmod 600 secrets/* diff --git a/src/app/__init__.py b/src/app/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/app/main.py b/src/app/main.py new file mode 100644 index 00000000..32fea189 --- /dev/null +++ b/src/app/main.py @@ -0,0 +1,378 @@ +import base64 +import binascii +import hashlib +import json +import os +import re +import secrets +import uuid +from datetime import datetime, timedelta, timezone + +import psycopg +from argon2 import PasswordHasher +from argon2.exceptions import VerifyMismatchError, InvalidHashError +from psycopg.errors import UniqueViolation +from psycopg_pool import ConnectionPool, PoolTimeout +from starlette.applications import Starlette +from starlette.requests import Request +from starlette.concurrency import run_in_threadpool +from starlette.responses import JSONResponse, Response +from starlette.routing import Route + +from . import migrate + +INSTANCE_ID = uuid.uuid4().hex[:8] +SESSION_TTL = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) +USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$") +KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") +ph = PasswordHasher() +# заранее посчитанный хеш — выравнивает время ответа для неизвестного username +DUMMY_HASH = ph.hash("dummy-password-for-timing") + + +def read_secret(name: str) -> str: + path = os.environ.get(name + "_FILE") + if path: + return open(path, encoding="utf-8").read().strip() + return os.environ[name] + + +DSN = read_secret("DATABASE_URL") +pool = ConnectionPool(DSN, min_size=2, max_size=int(os.environ.get("DB_POOL_MAX", "10")), + timeout=5, open=False, kwargs={"connect_timeout": 5}) + + +class ApiError(Exception): + def __init__(self, status, code, message, headers=None): + self.status, self.code, self.message, self.headers = status, code, message, headers or {} + + +def bad(msg="Неверный запрос"): + return ApiError(400, "invalid_request", msg) + + +def iso(dt: datetime) -> str: + return dt.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") + + +def parse_uuid(s): + try: + u = uuid.UUID(s) + if str(u) != s.lower(): + raise ValueError + return u + except (ValueError, AttributeError, TypeError): + raise bad("Неверный UUID") + + +def user_json(r): + return {"id": str(r[0]), "username": r[1], "display_name": r[2], "created_at": iso(r[3])} + + +def msg_json(r): + return {"id": str(r[0]), "chat_id": str(r[1]), "sender_id": str(r[2]), "text": r[3], "created_at": iso(r[4])} + + +def non_blank(s): + return isinstance(s, str) and s.strip() != "" + + +def body_json(request: Request, allowed: set, required: set): + ct = request.headers.get("content-type", "").split(";")[0].strip().lower() + if ct != "application/json": + raise ApiError(415, "unsupported_media_type", "Нужен application/json") + raw = request._body # прочитано заранее в обёртке + if len(raw) > MAX_BODY: + raise ApiError(413, "payload_too_large", "Слишком большое тело") + try: + data = json.loads(raw.decode("utf-8")) + except (ValueError, UnicodeError): + raise bad("Некорректный JSON") + if not isinstance(data, dict) or set(data) - allowed or required - set(data): + raise bad() + return data + + +def current_user(request: Request, conn): + auth = request.headers.get("authorization", "") + parts = auth.split(" ", 1) + hdr = {"WWW-Authenticate": 'Bearer realm="messenger"'} + if len(parts) != 2 or parts[0].lower() != "bearer" or not parts[1].strip(): + raise ApiError(401, "unauthorized", "Требуется аутентификация", hdr) + th = hashlib.sha256(parts[1].strip().encode()).digest() + row = conn.execute( + "SELECT u.id,u.username,u.display_name,u.created_at FROM sessions s JOIN users u ON u.id=s.user_id " + "WHERE s.token_hash=%s AND s.revoked_at IS NULL AND s.expires_at>now()", (th,)).fetchone() + if not row: + raise ApiError(401, "unauthorized", "Требуется аутентификация", hdr) + return row, th + + +MAX_BODY = 1024 * 1024 + + +async def read_body_limited(request: Request): + """Читает тело с лимитом: 413 до того, как всё тело окажется в памяти.""" + cl = request.headers.get("content-length") + if cl is not None and (not cl.isdigit() or int(cl) > MAX_BODY): + raise ApiError(413, "payload_too_large", "Слишком большое тело") + buf = bytearray() + async for chunk in request.stream(): + buf += chunk + if len(buf) > MAX_BODY: + raise ApiError(413, "payload_too_large", "Слишком большое тело") + request._body = bytes(buf) + + +def db(fn): + """Обёртка эндпоинта: соединение из пула, единая обработка ошибок.""" + async def wrapper(request: Request): + rid = request.headers.get("x-request-id") or uuid.uuid4().hex + try: + await read_body_limited(request) + resp = await run_in_threadpool(fn, request) + except ApiError as e: + resp = JSONResponse({"error": {"code": e.code, "message": e.message, "request_id": rid}}, + status_code=e.status, headers=e.headers) + except (PoolTimeout, psycopg.OperationalError): + resp = JSONResponse({"error": {"code": "unavailable", "message": "Сервис временно недоступен", + "request_id": rid}}, status_code=503) + except Exception: + resp = JSONResponse({"error": {"code": "internal_error", "message": "Внутренняя ошибка", + "request_id": rid}}, status_code=500) + resp.headers["X-Request-Id"] = rid + resp.headers["X-Instance-Id"] = INSTANCE_ID + return resp + return wrapper + + +def page_args(request: Request): + q = request.query_params + if len(q.getlist("limit")) > 1 or len(q.getlist("cursor")) > 1: + raise bad("limit/cursor можно указать один раз") + limit = 50 + if q.getlist("limit"): + t = q.get("limit") + if not (t.isascii() and t.isdigit()) or not 1 <= int(t) <= 100: + raise bad("limit") + limit = int(t) + return limit, q.get("cursor") or None + + +def enc_cursor(kind, scope, ts, id_): + return base64.urlsafe_b64encode(json.dumps([kind, scope, ts, str(id_)]).encode()).decode().rstrip("=") + + +def dec_cursor(c, kind, scope): + try: + v = json.loads(base64.urlsafe_b64decode(c + "=" * (-len(c) % 4))) + if v[0] != kind or v[1] != scope: + raise ValueError + return datetime.fromisoformat(v[2].replace("Z", "+00:00")), uuid.UUID(v[3]) + except Exception: + raise bad("cursor") + + +async def live(request): + return JSONResponse({"status": "ok"}, headers={"X-Request-Id": request.headers.get("x-request-id") or uuid.uuid4().hex, "X-Instance-Id": INSTANCE_ID}) + + +@db +def ready(request): + with pool.connection(timeout=2) as conn: + conn.execute("SELECT 1") + return JSONResponse({"status": "ok"}) + + +@db +def create_user(request): + d = body_json(request, {"username", "display_name", "password"}, {"username", "display_name", "password"}) + u, dn, pw = d["username"], d["display_name"], d["password"] + if not (isinstance(u, str) and USERNAME_RE.fullmatch(u)): + raise bad("username") + if not (non_blank(dn) and len(dn) <= 100): + raise bad("display_name") + if not (isinstance(pw, str) and 12 <= len(pw) <= 128): + raise bad("password") + h = ph.hash(pw) + with pool.connection() as conn: + try: + r = conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) " + "RETURNING id,username,display_name,created_at", (uuid.uuid4(), u, dn, h)).fetchone() + except UniqueViolation: + raise ApiError(409, "conflict", "Имя пользователя занято") + return JSONResponse(user_json(r), status_code=201) + + +@db +def login(request): + ch = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'} + fail = ApiError(401, "unauthorized", "Неверные учётные данные", ch) + auth = request.headers.get("authorization", "") + parts = auth.split(" ", 1) + if len(parts) != 2 or parts[0].lower() != "basic": + raise fail + try: + creds = base64.b64decode(parts[1].strip(), validate=True).decode("utf-8") + except (binascii.Error, UnicodeError): + raise fail + if ":" not in creds: + raise fail + username, password = creds.split(":", 1) + with pool.connection() as conn: + row = conn.execute("SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=%s", + (username,)).fetchone() + try: + ph.verify(row[4] if row else DUMMY_HASH, password) + ok = row is not None + except (VerifyMismatchError, InvalidHashError): + ok = False + if not ok: + raise fail + token = secrets.token_urlsafe(32) # 256 бит + exp = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL) + conn.execute("INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (%s,%s,%s)", + (hashlib.sha256(token.encode()).digest(), row[0], exp)) + return JSONResponse({"token": token, "token_type": "Bearer", "expires_at": iso(exp), "user": user_json(row)}, + status_code=201) + + +@db +def logout(request): + with pool.connection() as conn: + _, th = current_user(request, conn) + conn.execute("UPDATE sessions SET revoked_at=now() WHERE token_hash=%s", (th,)) + return Response(status_code=204) + + +@db +def me(request): + with pool.connection() as conn: + row, _ = current_user(request, conn) + return JSONResponse(user_json(row)) + + +def chat_json(conn, r): + members = [str(x[0]) for x in conn.execute( + "SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id", (r[0],))] + return {"id": str(r[0]), "title": r[1], "member_ids": members, "created_at": iso(r[2])} + + +@db +def create_chat(request): + with pool.connection() as conn: + user, _ = current_user(request, conn) + d = body_json(request, {"title", "member_ids"}, {"title", "member_ids"}) + t, m = d["title"], d["member_ids"] + if not (non_blank(t) and len(t) <= 100): + raise bad("title") + if not (isinstance(m, list) and 1 <= len(m) <= 100 and all(isinstance(x, str) for x in m)): + raise bad("member_ids") + ids = [parse_uuid(x) for x in m] + if len(set(ids)) != len(ids) or user[0] not in ids: + raise bad("member_ids") + found = conn.execute("SELECT count(*) FROM users WHERE id = ANY(%s)", (ids,)).fetchone()[0] + if found != len(ids): + raise bad("member_ids") + cid = uuid.uuid4() + with conn.transaction(): # чат и участники — атомарно + r = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at", (cid, t)).fetchone() + with conn.cursor() as cur: + cur.executemany("INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)", [(cid, i) for i in ids]) + return JSONResponse(chat_json(conn, r), status_code=201) + + +@db +def list_chats(request): + with pool.connection() as conn: + user, _ = current_user(request, conn) + limit, cursor = page_args(request) + args = [user[0]] + cond = "" + if cursor: + ts, i = dec_cursor(cursor, "chats", str(user[0])) + cond = "AND (c.created_at,c.id) > (%s,%s)" + args += [ts, i] + rows = conn.execute( + "SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id AND m.user_id=%s " + f"WHERE true {cond} ORDER BY c.created_at,c.id LIMIT %s", args + [limit + 1]).fetchall() + more = len(rows) > limit + rows = rows[:limit] + nxt = enc_cursor("chats", str(user[0]), iso(rows[-1][2]), rows[-1][0]) if more else None + return JSONResponse({"items": [chat_json(conn, r) for r in rows], "next_cursor": nxt}) + + +def get_chat_or_404(conn, user, chat_id): + cid = parse_uuid(chat_id) + r = conn.execute("SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m " + "ON m.chat_id=c.id WHERE c.id=%s AND m.user_id=%s", (cid, user[0])).fetchone() + if not r: + raise ApiError(404, "not_found", "Объект не найден") + return r + + +@db +def get_chat(request): + with pool.connection() as conn: + user, _ = current_user(request, conn) + r = get_chat_or_404(conn, user, request.path_params["chat_id"]) + return JSONResponse(chat_json(conn, r)) + + +@db +def send_message(request): + with pool.connection() as conn: + user, _ = current_user(request, conn) + cid = request.path_params["chat_id"] + chat = get_chat_or_404(conn, user, cid) + d = body_json(request, {"text"}, {"text"}) + t = d["text"] + if not (non_blank(t) and len(t) <= 4000): + raise bad("text") + r = 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(), chat[0], user[0], t)).fetchone() + return JSONResponse(msg_json(r), status_code=201) + + +@db +def list_messages(request): + with pool.connection() as conn: + user, _ = current_user(request, conn) + cid = request.path_params["chat_id"] + chat = get_chat_or_404(conn, user, cid) + limit, cursor = page_args(request) + args = [chat[0]] + cond = "" + if cursor: + ts, i = dec_cursor(cursor, "messages", str(chat[0])) + cond = "AND (created_at,id) > (%s,%s)" + args += [ts, i] + rows = conn.execute("SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=%s " + f"{cond} ORDER BY created_at,id LIMIT %s", args + [limit + 1]).fetchall() + more = len(rows) > limit + rows = rows[:limit] + nxt = enc_cursor("messages", str(chat[0]), iso(rows[-1][4]), rows[-1][0]) if more else None + return JSONResponse({"items": [msg_json(r) for r in rows], "next_cursor": nxt}) + + +async def lifespan(app): + migrate.run(DSN) + pool.open(wait=True, timeout=30) + yield + pool.close() + + +P = "/api/v1" +app = Starlette(lifespan=lifespan, routes=[ + Route("/health/live", live), + Route("/health/ready", ready), + Route(P + "/users", create_user, methods=["POST"]), + Route(P + "/users/me", me), + Route(P + "/auth/sessions", login, methods=["POST"]), + Route(P + "/auth/sessions/current", logout, methods=["DELETE"]), + Route(P + "/chats", create_chat, methods=["POST"]), + Route(P + "/chats", list_chats, methods=["GET"]), + Route(P + "/chats/{chat_id}", get_chat), + Route(P + "/chats/{chat_id}/messages", send_message, methods=["POST"]), + Route(P + "/chats/{chat_id}/messages", list_messages, methods=["GET"]), +]) diff --git a/src/app/migrate.py b/src/app/migrate.py new file mode 100644 index 00000000..0f512105 --- /dev/null +++ b/src/app/migrate.py @@ -0,0 +1,25 @@ +"""Версионируемые миграции: применяются по порядку, повторный запуск безопасен.""" +import pathlib +import psycopg + +DIR = pathlib.Path(__file__).resolve().parent.parent / "migrations" + + +def run(dsn: str) -> None: + with psycopg.connect(dsn, autocommit=True) as conn: + # advisory lock: несколько реплик/перезапусков не мигрируют одновременно + conn.execute("SELECT pg_advisory_lock(727001)") + try: + conn.execute( + "CREATE TABLE IF NOT EXISTS schema_migrations (" + "version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())" + ) + done = {r[0] for r in conn.execute("SELECT version FROM schema_migrations")} + for f in sorted(DIR.glob("*.sql")): + if f.name in done: + continue + with conn.transaction(): + conn.execute(f.read_text(encoding="utf-8")) + conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (f.name,)) + finally: + conn.execute("SELECT pg_advisory_unlock(727001)") diff --git a/src/migrations/001_init.sql b/src/migrations/001_init.sql new file mode 100644 index 00000000..28531688 --- /dev/null +++ b/src/migrations/001_init.sql @@ -0,0 +1,39 @@ +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 now() +); + +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 INDEX chats_created_idx ON chats (created_at, id); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id uuid NOT NULL REFERENCES users(id), + text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +-- keyset-пагинация истории: WHERE chat_id=$1 AND (created_at,id) > ($2,$3) ORDER BY created_at,id +CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id); + +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, -- sha256(token); сам токен не хранится + user_id uuid NOT NULL REFERENCES users(id), + expires_at timestamptz NOT NULL, + revoked_at timestamptz +); +CREATE INDEX sessions_expires_idx ON sessions (expires_at); diff --git a/src/requirements.txt b/src/requirements.txt new file mode 100644 index 00000000..89a404c2 --- /dev/null +++ b/src/requirements.txt @@ -0,0 +1,4 @@ +starlette==0.41.3 +uvicorn==0.32.1 +psycopg[binary,pool]==3.2.3 +argon2-cffi==23.1.0 diff --git a/student-tests/lab2_checks.py b/student-tests/lab2_checks.py new file mode 100644 index 00000000..87d14ef6 --- /dev/null +++ b/student-tests/lab2_checks.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""Собственные проверки lab2 (дополняют публичный smoke, ничего не ослабляют). + + python student-tests/lab2_checks.py --base-url http://localhost:8080 # основные + python student-tests/lab2_checks.py --base-url http://localhost:8080 --mode ttl # при SESSION_TTL_SECONDS=2 + +Только стандартная библиотека. Токены и пароли не печатаются. +""" +import argparse, base64, http.client, json, sys, threading, time, urllib.error, urllib.parse, urllib.request, uuid + +PW = "correct-horse-battery" +fails = [] + + +def call(base, method, path, body=None, headers=None, raw=None): + h = dict(headers or {}) + data = raw + if body is not None: + data = json.dumps(body).encode() + h.setdefault("Content-Type", "application/json") + req = urllib.request.Request(base + path, data=data, headers=h, method=method) + try: + with urllib.request.urlopen(req, timeout=15) as r: + return r.status, {k.lower(): v for k, v in r.headers.items()}, r.read() + except urllib.error.HTTPError as e: + return e.code, {k.lower(): v for k, v in e.headers.items()}, e.read() + + +def post_big(base, path, size): + """POST тела size байт; сервер может ответить 413 и закрыть соединение раньше, чем тело отправлено.""" + u = urllib.parse.urlsplit(base) + conn = http.client.HTTPConnection(u.hostname, u.port, timeout=15) + conn.putrequest("POST", u.path + path) + conn.putheader("Content-Type", "application/json") + conn.putheader("Content-Length", str(size)) + conn.endheaders() + try: + conn.send(b"{" + b" " * (size - 2) + b"}") + except OSError: + pass # сервер уже ответил и закрыл соединение + try: + return conn.getresponse().status + except (OSError, http.client.HTTPException) as e: + return "нет ответа: %s" % type(e).__name__ + finally: + conn.close() + + +def js(b): + try: + return json.loads(b) + except ValueError: + return None + + +def check(name, ok, detail=""): + print(("PASS" if ok else "FAIL") + ": " + name + ("" if ok else " -> " + detail)) + if not ok: + fails.append(name) + + +def basic(u, p): + return {"Authorization": "Basic " + base64.b64encode(f"{u}:{p}".encode()).decode()} + + +def bearer(t): + return {"Authorization": "Bearer " + t} + + +class Api: + def __init__(self, base): + self.base = base + "/api/v1" + + def __call__(self, *a, **k): + return call(self.base, *a, **k) + + def user(self, prefix="u"): + name = f"{prefix}_{uuid.uuid4().hex[:10]}" + s, _, b = self("POST", "/users", {"username": name, "display_name": name, "password": PW}) + assert s == 201, f"create user: {s}" + u = js(b) + s, _, b = self("POST", "/auth/sessions", headers=basic(name, PW)) + assert s == 201, f"login: {s}" + return name, u["id"], js(b)["token"] + + +def main_checks(api): + a_name, a_id, a_tok = api.user("alice") + b_name, b_id, b_tok = api.user("bob") + c_name, c_id, c_tok = api.user("carol") + + # --- регистрация + s, _, _ = api("POST", "/users", {"username": a_name, "display_name": "x", "password": PW}) + check("повторный username -> 409", s == 409, str(s)) + s, _, b = api("POST", "/users", {"username": "x_" + uuid.uuid4().hex[:8], "display_name": "x", "password": "short"}) + check("пароль короче 12 -> 400", s == 400, str(s)) + s, _, b = api("POST", "/users", {"username": "x_" + uuid.uuid4().hex[:8], "display_name": "x", "password": PW, "extra": 1}) + check("лишнее поле -> 400", s == 400, str(s)) + s, _, b = api("GET", "/users/me", headers=bearer(a_tok)) + me = js(b) or {} + check("User не содержит пароль/hash/токен", s == 200 and not ({"password", "password_hash", "token"} & set(me)), str(sorted(me))) + + res = [] + rname = "race_" + uuid.uuid4().hex[:10] + def reg(): + res.append(api("POST", "/users", {"username": rname, "display_name": "r", "password": PW})[0]) + ts = [threading.Thread(target=reg) for _ in range(10)] + [t.start() for t in ts]; [t.join() for t in ts] + check("гонка одинакового username: ровно один 201, остальные 409", sorted(res) == [201] + [409] * 9, str(sorted(res))) + + # --- вход + s1, h1, b1 = api("POST", "/auth/sessions", headers=basic(a_name, "wrong-password-123")) + s2, h2, b2 = api("POST", "/auth/sessions", headers=basic("nosuchuser_zz", PW)) + e1, e2 = (js(b1) or {}).get("error", {}), (js(b2) or {}).get("error", {}) + check("неверный пароль и неизвестный пользователь неразличимы (401, тот же code/message/заголовок)", + s1 == s2 == 401 and e1.get("code") == e2.get("code") and e1.get("message") == e2.get("message") + and h1.get("www-authenticate") == h2.get("www-authenticate") == 'Basic realm="messenger", charset="UTF-8"', + f"{s1}/{s2} {h1.get('www-authenticate')}") + s, _, _ = api("POST", "/auth/sessions", {"username": a_name, "password": PW}) + check("вход JSON-телом без Basic -> 401", s == 401, str(s)) + s, _, _ = api("POST", "/auth/sessions", headers=bearer(a_tok)) + check("Bearer на POST /auth/sessions -> 401", s == 401, str(s)) + s, h, b = api("POST", "/auth/sessions", headers=basic(a_name, PW)) + d = js(b) or {} + check("токен >=256 бит, token_type Bearer", s == 201 and len(d.get("token", "")) >= 43 and d.get("token_type") == "Bearer", str(s)) + + # --- бизнес-endpoint принимают только Bearer + s, h, _ = api("GET", "/users/me", headers=basic(a_name, PW)) + check("Basic на бизнес-endpoint -> 401 + WWW-Authenticate: Bearer", s == 401 and h.get("www-authenticate", "").startswith("Bearer"), str(s)) + s, _, _ = api("GET", "/users/me", headers={"X-User-Id": a_id}) + check("один X-User-Id доступа не даёт", s == 401, str(s)) + s, _, b = api("GET", "/users/me", headers={**bearer(a_tok), "X-User-Id": b_id}) + check("X-User-Id игнорируется: владелец определяется токеном", s == 200 and (js(b) or {}).get("id") == a_id, str(s)) + s, _, _ = api("GET", "/users/me", headers=bearer("x" * 43)) + check("неизвестный токен -> 401", s == 401, str(s)) + + # --- запрос-идентификатор в ошибках + s, h, b = api("GET", "/chats") + check("X-Request-Id совпадает с request_id в теле ошибки", s == 401 and h.get("x-request-id") == (js(b) or {}).get("error", {}).get("request_id"), str(s)) + + # --- чаты и доступ + s, _, b = api("GET", "/chats", headers=bearer(a_tok)) + before = len((js(b) or {}).get("items", [])) + s, _, b = api("POST", "/chats", {"title": "t", "member_ids": [a_id, str(uuid.uuid4())]}, bearer(a_tok)) + check("чат с неизвестным участником -> 400", s == 400, str(s)) + s, _, b = api("GET", "/chats", headers=bearer(a_tok)) + check("после отказа новый чат не появился (нет частичной записи)", len((js(b) or {}).get("items", [])) == before) + s, _, b = api("POST", "/chats", {"title": "ab", "member_ids": [a_id, b_id]}, bearer(a_tok)) + chat = js(b) or {} + check("чат создан с обоими участниками", s == 201 and sorted(chat.get("member_ids", [])) == sorted([a_id, b_id]), str(s)) + cid = chat.get("id", "") + s, _, _ = api("POST", "/chats", {"title": "ab", "member_ids": [b_id]}, bearer(a_tok)) + check("создатель обязан быть среди member_ids -> 400", s == 400, str(s)) + for path in (f"/chats/{cid}", f"/chats/{cid}/messages"): + s, _, _ = api("GET", path, headers=bearer(c_tok)) + check(f"посторонний: GET {path.split(cid)[1] or '/chat'} -> 404", s == 404, str(s)) + s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "hi"}, bearer(c_tok)) + check("посторонний не может писать -> 404", s == 404, str(s)) + for path in ("/chats/not-a-uuid", "/chats/not-a-uuid/messages"): + s, _, _ = api("GET", path, headers=bearer(a_tok)) + check(f"неверный UUID {path} -> 400", s == 400, str(s)) + s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "hi", "sender_id": b_id}, bearer(a_tok)) + check("sender_id в запросе не принимается -> 400", s == 400, str(s)) + s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": " "}, bearer(a_tok)) + check("пробельный текст -> 400", s == 400, str(s)) + s, _, b = api("POST", f"/chats/{cid}/messages", {"text": "привет 👋"}, bearer(b_tok)) + check("отправитель берётся из токена", s == 201 and (js(b) or {}).get("sender_id") == b_id, str(s)) + + # --- пагинация + for i in range(5): + api("POST", f"/chats/{cid}/messages", {"text": f"m{i}"}, bearer(a_tok)) + seen, cur, pages = [], None, 0 + while True: + s, _, b = api("GET", f"/chats/{cid}/messages?limit=2" + (f"&cursor={cur}" if cur else ""), headers=bearer(a_tok)) + d = js(b) or {} + seen += [m["id"] for m in d.get("items", [])] + pages += 1 + cur = d.get("next_cursor") + if not cur or pages > 10: + break + check("пагинация limit=2: без повторов, все 6 сообщений", len(seen) == len(set(seen)) == 6, f"{len(seen)}/{len(set(seen))}") + s, _, b = api("GET", f"/chats/{cid}/messages?limit=2", headers=bearer(a_tok)) + cur = (js(b) or {}).get("next_cursor") + s, _, b = api("POST", "/chats", {"title": "other", "member_ids": [a_id]}, bearer(a_tok)) + other = (js(b) or {}).get("id") + s, _, _ = api("GET", f"/chats/{other}/messages?cursor={cur}", headers=bearer(a_tok)) + check("cursor от другого чата -> 400", s == 400, str(s)) + for q in ("limit=0", "limit=101", "limit=abc", "limit=%2B5", "limit=2&limit=3"): + s, _, _ = api("GET", f"/chats/{cid}/messages?{q}", headers=bearer(a_tok)) + check(f"?{q} -> 400", s == 400, str(s)) + + # --- тело запроса + s = post_big(api.base, "/users", 1100 * 1024) + check("тело >1 MiB -> 413", s == 413, str(s)) + s, _, _ = api("POST", "/users", raw=b"{}", headers={"Content-Type": "text/plain"}) + check("не JSON Content-Type -> 415", s == 415, str(s)) + s, _, _ = api("POST", "/users", raw=b"{", headers={"Content-Type": "application/json"}) + check("битый JSON -> 400", s == 400, str(s)) + + # --- logout (в конце: отзывает токен) + s, _, _ = api("DELETE", "/auth/sessions/current", headers=bearer(a_tok)) + check("logout -> 204", s == 204, str(s)) + s, h, _ = api("DELETE", "/auth/sessions/current", headers=bearer(a_tok)) + check("повторный logout с отозванным токеном -> 401", s == 401, str(s)) + s, h, _ = api("GET", "/users/me", headers=bearer(a_tok)) + check("отозванный токен -> 401 + WWW-Authenticate: Bearer", s == 401 and h.get("www-authenticate", "").startswith("Bearer"), str(s)) + s, _, _ = api("GET", "/users/me", headers=bearer(b_tok)) + check("logout одного пользователя не затрагивает чужие сессии", s == 200, str(s)) + + +def ttl_checks(api): + name = api.user("ttl")[0] + s, _, b = api("POST", "/auth/sessions", headers=basic(name, PW)) + d = js(b) or {} + tok = d.get("token", "") + s0, _, _ = api("GET", "/users/me", headers=bearer(tok)) + check("TTL: сразу после входа токен действует (200)", s0 == 200, str(s0)) + time.sleep(3.5) + s1, h, _ = api("GET", "/users/me", headers=bearer(tok)) + check("TTL: через 3.5 с при SESSION_TTL_SECONDS=2 токен истёк (401)", s1 == 401 and h.get("www-authenticate", "").startswith("Bearer"), str(s1)) + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--base-url", default="http://localhost:8080") + ap.add_argument("--mode", choices=["main", "ttl"], default="main") + a = ap.parse_args() + api = Api(a.base_url.rstrip("/")) + (ttl_checks if a.mode == "ttl" else main_checks)(api) + print(("FAIL: %d проверок не прошли: %s" % (len(fails), "; ".join(fails))) if fails else "PASS: все проверки режима '%s'" % a.mode) + sys.exit(1 if fails else 0) -- 2.54.0 From 326f96841466fe2edecacd241117098caad30b1f Mon Sep 17 00:00:00 2001 From: Conloty <149334964+Conloty@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:55:43 +0300 Subject: [PATCH 2/2] lab2: evidence. --- evidence/00-clean-start.txt | 337 +++++++++++++++++ evidence/01-env.txt | 37 ++ evidence/02-smoke.txt | 7 + evidence/03-student-checks.txt | 44 +++ evidence/04-persistence.txt | 29 ++ evidence/05-db-schema.txt | 109 ++++++ evidence/06-migrations.txt | 30 ++ evidence/07-ttl.txt | 23 ++ evidence/08-db-down.txt | 14 + evidence/09-git-hygiene.txt | 7 + evidence/summary.txt | 669 +++++++++++++++++++++++++++++++++ 11 files changed, 1306 insertions(+) create mode 100644 evidence/00-clean-start.txt create mode 100644 evidence/01-env.txt create mode 100644 evidence/02-smoke.txt create mode 100644 evidence/03-student-checks.txt create mode 100644 evidence/04-persistence.txt create mode 100644 evidence/05-db-schema.txt create mode 100644 evidence/06-migrations.txt create mode 100644 evidence/07-ttl.txt create mode 100644 evidence/08-db-down.txt create mode 100644 evidence/09-git-hygiene.txt create mode 100644 evidence/summary.txt diff --git a/evidence/00-clean-start.txt b/evidence/00-clean-start.txt new file mode 100644 index 00000000..4ecedb35 --- /dev/null +++ b/evidence/00-clean-start.txt @@ -0,0 +1,337 @@ +# 00 чистый старт (2026-11-12T18:04:45Z) +$ docker compose down -v + Volume mtusi2026lab2_pgdata Removing + Volume mtusi2026lab2_pgdata Removed +$ sh scripts/setup-secrets.sh +secrets: ok (значения не печатаются) +$ docker compose up -d --build + postgres Pulling + 500aaa681781 Pulling fs layer + 6886cb0fa181 Pulling fs layer + 09852ea151b6 Pulling fs layer + 3c23ffc3610d Pulling fs layer + da9db072f522 Pulling fs layer + 7c35d0b2112f Pulling fs layer + 754dcd3183db Pulling fs layer + 5b2b0e42c692 Pulling fs layer + d68e4f14dc32 Pulling fs layer + b6fcda863f21 Pulling fs layer + 4f90fd4705e0 Pulling fs layer + 6886cb0fa181 Download complete + 500aaa681781 Download complete + 754dcd3183db Downloading [==================================================>] 5.416kB/5.416kB + b6fcda863f21 Download complete + 7c35d0b2112f Download complete + 5b2b0e42c692 Download complete + 09852ea151b6 Download complete + 4f90fd4705e0 Download complete + 754dcd3183db Download complete + 3c23ffc3610d Download complete + d68e4f14dc32 Downloading [> ] 1.049MB/94.39MB + da9db072f522 Downloading [==============> ] 1.049MB/3.624MB + d68e4f14dc32 Downloading [> ] 1.049MB/94.39MB + da9db072f522 Downloading [==============> ] 1.049MB/3.624MB + d68e4f14dc32 Downloading [> ] 1.049MB/94.39MB + da9db072f522 Downloading [==============> ] 1.049MB/3.624MB + d68e4f14dc32 Downloading [=> ] 2.097MB/94.39MB + d68e4f14dc32 Downloading [=> ] 2.097MB/94.39MB + da9db072f522 Downloading [==============> ] 1.049MB/3.624MB + d68e4f14dc32 Downloading [=> ] 3.146MB/94.39MB + da9db072f522 Downloading [============================> ] 2.097MB/3.624MB + d68e4f14dc32 Downloading [=> ] 3.146MB/94.39MB + da9db072f522 Downloading [===========================================> ] 3.146MB/3.624MB + d68e4f14dc32 Downloading [==> ] 4.194MB/94.39MB + da9db072f522 Download complete + da9db072f522 Extracting 1 s + d68e4f14dc32 Downloading [==> ] 4.194MB/94.39MB + da9db072f522 Extracting 1 s + d68e4f14dc32 Downloading [==> ] 4.194MB/94.39MB + da9db072f522 Pull complete + d68e4f14dc32 Downloading [==> ] 5.243MB/94.39MB + 7c35d0b2112f Extracting 1 s + d68e4f14dc32 Downloading [===> ] 6.291MB/94.39MB + 7c35d0b2112f Pull complete + 3c23ffc3610d Pull complete + d68e4f14dc32 Downloading [===> ] 6.291MB/94.39MB + 6886cb0fa181 Pull complete + 4f90fd4705e0 Pull complete + d68e4f14dc32 Downloading [===> ] 7.34MB/94.39MB + d68e4f14dc32 Downloading [====> ] 8.389MB/94.39MB + d68e4f14dc32 Downloading [====> ] 8.389MB/94.39MB + d68e4f14dc32 Downloading [====> ] 9.437MB/94.39MB + d68e4f14dc32 Downloading [=====> ] 10.49MB/94.39MB + d68e4f14dc32 Downloading [=====> ] 10.49MB/94.39MB + d68e4f14dc32 Downloading [=====> ] 10.49MB/94.39MB + d68e4f14dc32 Downloading [======> ] 11.53MB/94.39MB + d68e4f14dc32 Downloading [======> ] 12.58MB/94.39MB + d68e4f14dc32 Downloading [======> ] 12.58MB/94.39MB + d68e4f14dc32 Downloading [=======> ] 13.63MB/94.39MB + d68e4f14dc32 Downloading [=======> ] 14.02MB/94.39MB + d68e4f14dc32 Downloading [=======> ] 14.68MB/94.39MB + d68e4f14dc32 Downloading [========> ] 15.27MB/94.39MB + d68e4f14dc32 Downloading [========> ] 16.36MB/94.39MB + d68e4f14dc32 Downloading [========> ] 16.78MB/94.39MB + d68e4f14dc32 Downloading [=========> ] 17.83MB/94.39MB + d68e4f14dc32 Downloading [=========> ] 17.83MB/94.39MB + d68e4f14dc32 Downloading [=========> ] 17.83MB/94.39MB + d68e4f14dc32 Downloading [=========> ] 18.87MB/94.39MB + d68e4f14dc32 Downloading [==========> ] 19.92MB/94.39MB + d68e4f14dc32 Downloading [===========> ] 20.97MB/94.39MB + d68e4f14dc32 Downloading [===========> ] 22.02MB/94.39MB + d68e4f14dc32 Downloading [===========> ] 22.02MB/94.39MB + d68e4f14dc32 Downloading [============> ] 23.07MB/94.39MB + d68e4f14dc32 Downloading [============> ] 24.12MB/94.39MB + d68e4f14dc32 Downloading [=============> ] 25.17MB/94.39MB + d68e4f14dc32 Downloading [=============> ] 26.21MB/94.39MB + d68e4f14dc32 Downloading [=============> ] 26.21MB/94.39MB + d68e4f14dc32 Downloading [==============> ] 27.26MB/94.39MB + d68e4f14dc32 Downloading [===============> ] 29.36MB/94.39MB + d68e4f14dc32 Downloading [===============> ] 29.36MB/94.39MB + d68e4f14dc32 Downloading [================> ] 30.41MB/94.39MB + d68e4f14dc32 Downloading [================> ] 31.46MB/94.39MB + d68e4f14dc32 Downloading [=================> ] 32.51MB/94.39MB + d68e4f14dc32 Downloading [=================> ] 33.55MB/94.39MB + d68e4f14dc32 Downloading [=================> ] 33.55MB/94.39MB + d68e4f14dc32 Downloading [==================> ] 34.6MB/94.39MB + d68e4f14dc32 Downloading [==================> ] 35.65MB/94.39MB + d68e4f14dc32 Downloading [===================> ] 37.75MB/94.39MB + d68e4f14dc32 Downloading [====================> ] 38.8MB/94.39MB + d68e4f14dc32 Downloading [=====================> ] 39.85MB/94.39MB + d68e4f14dc32 Downloading [=====================> ] 39.85MB/94.39MB + d68e4f14dc32 Downloading [======================> ] 41.94MB/94.39MB + d68e4f14dc32 Downloading [======================> ] 42.99MB/94.39MB + d68e4f14dc32 Downloading [======================> ] 42.99MB/94.39MB + d68e4f14dc32 Downloading [=======================> ] 45.09MB/94.39MB + d68e4f14dc32 Downloading [=======================> ] 45.09MB/94.39MB + d68e4f14dc32 Downloading [========================> ] 45.65MB/94.39MB + d68e4f14dc32 Downloading [========================> ] 47.19MB/94.39MB + d68e4f14dc32 Downloading [==========================> ] 49.28MB/94.39MB + d68e4f14dc32 Downloading [==========================> ] 50.33MB/94.39MB + d68e4f14dc32 Downloading [==========================> ] 50.33MB/94.39MB + d68e4f14dc32 Downloading [===========================> ] 52.43MB/94.39MB + d68e4f14dc32 Downloading [============================> ] 53.48MB/94.39MB + d68e4f14dc32 Downloading [============================> ] 54.53MB/94.39MB + d68e4f14dc32 Downloading [=============================> ] 55.57MB/94.39MB + d68e4f14dc32 Downloading [=============================> ] 56.62MB/94.39MB + d68e4f14dc32 Downloading [=============================> ] 56.62MB/94.39MB + d68e4f14dc32 Downloading [==============================> ] 57.67MB/94.39MB + d68e4f14dc32 Downloading [===============================> ] 59.77MB/94.39MB + d68e4f14dc32 Downloading [================================> ] 60.82MB/94.39MB + d68e4f14dc32 Downloading [================================> ] 61.87MB/94.39MB + d68e4f14dc32 Downloading [=================================> ] 62.91MB/94.39MB + d68e4f14dc32 Downloading [=================================> ] 63.96MB/94.39MB + d68e4f14dc32 Downloading [==================================> ] 65.01MB/94.39MB + d68e4f14dc32 Downloading [==================================> ] 66.06MB/94.39MB + d68e4f14dc32 Downloading [==================================> ] 66.06MB/94.39MB + d68e4f14dc32 Downloading [===================================> ] 67.11MB/94.39MB + d68e4f14dc32 Downloading [====================================> ] 68.16MB/94.39MB + d68e4f14dc32 Downloading [====================================> ] 69.21MB/94.39MB + d68e4f14dc32 Downloading [=====================================> ] 71.27MB/94.39MB + d68e4f14dc32 Downloading [======================================> ] 72.35MB/94.39MB + d68e4f14dc32 Downloading [======================================> ] 73.4MB/94.39MB + d68e4f14dc32 Downloading [=======================================> ] 74.45MB/94.39MB + d68e4f14dc32 Downloading [=======================================> ] 75.5MB/94.39MB + d68e4f14dc32 Downloading [=======================================> ] 75.5MB/94.39MB + d68e4f14dc32 Downloading [========================================> ] 76.55MB/94.39MB + d68e4f14dc32 Downloading [=========================================> ] 77.59MB/94.39MB + d68e4f14dc32 Downloading [==========================================> ] 79.69MB/94.39MB + d68e4f14dc32 Downloading [==========================================> ] 80.74MB/94.39MB + d68e4f14dc32 Downloading [===========================================> ] 81.79MB/94.39MB + d68e4f14dc32 Downloading [===========================================> ] 82.84MB/94.39MB + d68e4f14dc32 Downloading [============================================> ] 83.54MB/94.39MB + d68e4f14dc32 Downloading [============================================> ] 84.93MB/94.39MB + d68e4f14dc32 Downloading [============================================> ] 84.93MB/94.39MB + d68e4f14dc32 Downloading [=============================================> ] 85.98MB/94.39MB + d68e4f14dc32 Downloading [=============================================> ] 85.98MB/94.39MB + d68e4f14dc32 Downloading [=============================================> ] 85.98MB/94.39MB + d68e4f14dc32 Downloading [==============================================> ] 88.08MB/94.39MB + d68e4f14dc32 Downloading [==============================================> ] 88.08MB/94.39MB + d68e4f14dc32 Downloading [===============================================> ] 89.13MB/94.39MB + d68e4f14dc32 Downloading [================================================> ] 91.23MB/94.39MB + d68e4f14dc32 Downloading [================================================> ] 91.23MB/94.39MB + d68e4f14dc32 Downloading [================================================> ] 92.27MB/94.39MB + d68e4f14dc32 Downloading [================================================> ] 92.27MB/94.39MB + d68e4f14dc32 Downloading [================================================> ] 92.27MB/94.39MB + d68e4f14dc32 Downloading [==================================================>] 94.39MB/94.39MB + d68e4f14dc32 Downloading [==================================================>] 94.39MB/94.39MB + d68e4f14dc32 Downloading [==================================================>] 94.39MB/94.39MB + d68e4f14dc32 Download complete + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + b6fcda863f21 Pull complete + 5b2b0e42c692 Pull complete + d68e4f14dc32 Pull complete + 500aaa681781 Pull complete + 09852ea151b6 Pull complete + 754dcd3183db Pull complete + postgres Pulled +Compose can now delegate builds to bake for better performance. + To do so, set COMPOSE_BAKE=true. +#0 building with "desktop-linux" instance using docker driver + +#1 [api internal] load build definition from Dockerfile +#1 transferring dockerfile: 500B 0.0s done +#1 DONE 0.1s + +#2 [api internal] load metadata for docker.io/library/python:3.12.7-slim-bookworm +#2 DONE 3.0s + +#3 [api internal] load .dockerignore +#3 transferring context: 216B done +#3 DONE 0.0s + +#4 [api internal] load build context +#4 DONE 0.0s + +#5 [api 1/6] FROM docker.io/library/python:3.12.7-slim-bookworm@sha256:60d9996b6a8a3689d36db740b49f4327be3be09a21122bd02fb8895abb38b50d +#5 resolve docker.io/library/python:3.12.7-slim-bookworm@sha256:60d9996b6a8a3689d36db740b49f4327be3be09a21122bd02fb8895abb38b50d 0.0s done +#5 DONE 0.0s + +#5 [api 1/6] FROM docker.io/library/python:3.12.7-slim-bookworm@sha256:60d9996b6a8a3689d36db740b49f4327be3be09a21122bd02fb8895abb38b50d +#5 CACHED + +#4 [api internal] load build context +#4 transferring context: 18.27kB 0.0s done +#4 DONE 0.1s + +#6 [api 2/6] WORKDIR /app +#6 DONE 0.3s + +#7 [api 3/6] COPY src/requirements.txt . +#7 DONE 0.0s + +#8 [api 4/6] RUN pip install --no-cache-dir -r requirements.txt +#8 3.470 Collecting starlette==0.41.3 (from -r requirements.txt (line 1)) +#8 4.000 Downloading starlette-0.41.3-py3-none-any.whl.metadata (6.0 kB) +#8 4.333 Collecting uvicorn==0.32.1 (from -r requirements.txt (line 2)) +#8 4.440 Downloading uvicorn-0.32.1-py3-none-any.whl.metadata (6.6 kB) +#8 4.634 Collecting psycopg==3.2.3 (from psycopg[binary,pool]==3.2.3->-r requirements.txt (line 3)) +#8 4.740 Downloading psycopg-3.2.3-py3-none-any.whl.metadata (4.3 kB) +#8 5.137 Collecting argon2-cffi==23.1.0 (from -r requirements.txt (line 4)) +#8 5.244 Downloading argon2_cffi-23.1.0-py3-none-any.whl.metadata (5.2 kB) +#8 5.540 Collecting anyio<5,>=3.4.0 (from starlette==0.41.3->-r requirements.txt (line 1)) +#8 5.647 Downloading anyio-4.16.0-py3-none-any.whl.metadata (4.7 kB) +#8 5.977 Collecting click>=7.0 (from uvicorn==0.32.1->-r requirements.txt (line 2)) +#8 6.083 Downloading click-8.5.1-py3-none-any.whl.metadata (2.6 kB) +#8 6.575 Collecting h11>=0.8 (from uvicorn==0.32.1->-r requirements.txt (line 2)) +#8 6.682 Downloading h11-0.16.0-py3-none-any.whl.metadata (8.3 kB) +#8 7.089 Collecting typing-extensions>=4.6 (from psycopg==3.2.3->psycopg[binary,pool]==3.2.3->-r requirements.txt (line 3)) +#8 7.197 Downloading typing_extensions-4.16.0-py3-none-any.whl.metadata (3.3 kB) +#8 7.436 Collecting argon2-cffi-bindings (from argon2-cffi==23.1.0->-r requirements.txt (line 4)) +#8 7.542 Downloading argon2_cffi_bindings-26.1.0-cp310-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl.metadata (7.5 kB) +#8 12.83 Collecting psycopg-binary==3.2.3 (from psycopg[binary,pool]==3.2.3->-r requirements.txt (line 3)) +#8 12.94 Downloading psycopg_binary-3.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (2.8 kB) +#8 13.22 Collecting psycopg-pool (from psycopg[binary,pool]==3.2.3->-r requirements.txt (line 3)) +#8 13.33 Downloading psycopg_pool-3.3.3-py3-none-any.whl.metadata (2.8 kB) +#8 13.63 Collecting idna>=2.8 (from anyio<5,>=3.4.0->starlette==0.41.3->-r requirements.txt (line 1)) +#8 13.73 Downloading idna-3.20-py3-none-any.whl.metadata (7.2 kB) +#8 17.93 Collecting cffi>=1.0.1 (from argon2-cffi-bindings->argon2-cffi==23.1.0->-r requirements.txt (line 4)) +#8 18.50 Downloading cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (2.5 kB) +#8 18.65 Collecting pycparser (from cffi>=1.0.1->argon2-cffi-bindings->argon2-cffi==23.1.0->-r requirements.txt (line 4)) +#8 18.76 Downloading pycparser-3.12-py3-none-any.whl.metadata (9.7 kB) +#8 18.95 Downloading starlette-0.41.3-py3-none-any.whl (73 kB) +#8 19.71 Downloading uvicorn-0.32.1-py3-none-any.whl (63 kB) +#8 20.39 Downloading psycopg-3.2.3-py3-none-any.whl (197 kB) +#8 24.93 Downloading argon2_cffi-23.1.0-py3-none-any.whl (15 kB) +#8 25.35 Downloading psycopg_binary-3.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.2 MB) +#8 114.8 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.2/4.2 MB 48.1 kB/s eta 0:00:00 +#8 114.9 Downloading anyio-4.16.0-py3-none-any.whl (134 kB) +#8 116.6 Downloading click-8.5.1-py3-none-any.whl (126 kB) +#8 118.1 Downloading h11-0.16.0-py3-none-any.whl (37 kB) +#8 118.5 Downloading typing_extensions-4.16.0-py3-none-any.whl (45 kB) +#8 119.0 Downloading argon2_cffi_bindings-26.1.0-cp310-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl (26 kB) +#8 119.3 Downloading psycopg_pool-3.3.3-py3-none-any.whl (40 kB) +#8 119.9 Downloading cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (221 kB) +#8 123.5 Downloading idna-3.20-py3-none-any.whl (69 kB) +#8 124.3 Downloading pycparser-3.12-py3-none-any.whl (62 kB) +#8 125.4 Installing collected packages: typing-extensions, pycparser, psycopg-binary, idna, h11, click, uvicorn, psycopg-pool, psycopg, cffi, anyio, starlette, argon2-cffi-bindings, argon2-cffi +#8 126.4 Successfully installed anyio-4.16.0 argon2-cffi-23.1.0 argon2-cffi-bindings-26.1.0 cffi-2.1.1 click-8.5.1 h11-0.16.0 idna-3.20 psycopg-3.2.3 psycopg-binary-3.2.3 psycopg-pool-3.3.3 pycparser-3.12 starlette-0.41.3 typing-extensions-4.16.0 uvicorn-0.32.1 +#8 126.4 WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable.It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning. +#8 126.9 +#8 126.9 [notice] A new release of pip is available: 24.2 -> 26.3 +#8 126.9 [notice] To update, run: pip install --upgrade pip +#8 DONE 127.2s + +#9 [api 5/6] COPY src/ . +#9 DONE 0.1s + +#10 [api 6/6] RUN useradd -r -u 10001 appuser +#10 0.477 useradd warning: appuser's uid 10001 is greater than SYS_UID_MAX 999 +#10 DONE 0.5s + +#11 [api] exporting to image +#11 exporting layers +#11 exporting layers 0.9s done +#11 exporting manifest sha256:2e1cc496adb1045607f08bb61ac4f573f784e82fdf62ec3d61e7baaa95bffcc9 0.0s done +#11 exporting config sha256:23ae9e77c4d2fee678bf455531777f07f6d77a0c928ab9092130325030805f1c 0.0s done +#11 exporting attestation manifest sha256:f9af64a0e5f7d2e5fbe8d182bb92bcac260b5cd1b64ddb99ea6be12c6d80a3fb 0.0s done +#11 exporting manifest list sha256:bf04714d16cb9b11addf8ab71caa4754875e7b55ffb419aff89f2e77a63b4248 0.0s done +#11 naming to docker.io/library/mtusi2026lab2-api:latest done +#11 unpacking to docker.io/library/mtusi2026lab2-api:latest +#11 unpacking to docker.io/library/mtusi2026lab2-api:latest 0.4s done +#11 DONE 1.4s + +#12 [api] resolving provenance for metadata file +#12 DONE 0.0s + api Built + Network mtusi2026lab2_default Creating + Network mtusi2026lab2_default Created + Volume "mtusi2026lab2_pgdata" Creating + Volume "mtusi2026lab2_pgdata" Created + Container mtusi2026lab2-postgres-1 Creating + Container mtusi2026lab2-postgres-1 Created + Container mtusi2026lab2-api-1 Creating + Container mtusi2026lab2-api-1 Created + Container mtusi2026lab2-postgres-1 Starting + Container mtusi2026lab2-postgres-1 Started + Container mtusi2026lab2-postgres-1 Waiting + Container mtusi2026lab2-postgres-1 Healthy + Container mtusi2026lab2-api-1 Starting + Container mtusi2026lab2-api-1 Started +ready через 164 с после запуска up diff --git a/evidence/01-env.txt b/evidence/01-env.txt new file mode 100644 index 00000000..90bf72e6 --- /dev/null +++ b/evidence/01-env.txt @@ -0,0 +1,37 @@ +# 01 окружение (2026-11-12T18:52:34Z) +commit: ac54d4cfde5fa2876fdfedf55fd7d5840c33cdac +git status: +?? evidence/00-clean-start.txt +?? evidence/01-env.txt +?? evidence/02-smoke.txt +?? evidence/03-student-checks.txt +?? evidence/04-persistence.txt +?? evidence/05-db-schema.txt +?? evidence/06-migrations.txt +?? evidence/07-ttl.txt +?? evidence/08-db-down.txt +?? evidence/09-git-hygiene.txt +?? evidence/summary.txt +$ docker version +client=28.0.4 server=28.0.4 os=linux/amd64 +$ docker compose version +Docker Compose version v2.34.0-desktop.1 +python: Python 3.11.5 +$ docker compose config --quiet +compose config: OK +$ docker compose images +CONTAINER REPOSITORY TAG IMAGE ID SIZE +mtusi2026lab2-api-1 mtusi2026lab2-api latest bf04714d16cb 52.1MB +mtusi2026lab2-postgres-1 postgres 16.4-alpine 5660c2cbfea5 99.2MB +$ docker compose ps +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab2-api-1 mtusi2026lab2-api "uvicorn app.main:ap…" api 44 minutes ago Up 44 minutes (healthy) 127.0.0.1:8080->8080/tcp +mtusi2026lab2-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 45 minutes ago Up 44 minutes (healthy) 5432/tcp +$ docker volume ls (pgdata) +local mtusi2026lab2_pgdata +$ docker stats --no-stream +NAME CPU % MEM USAGE / LIMIT +mtusi2026lab2-api-1 0.16% 35.07MiB / 7.694GiB +mtusi2026lab2-postgres-1 0.00% 22.8MiB / 7.694GiB +$ docker info (лимиты хоста) +CPUs=16 Mem=8261029888 diff --git a/evidence/02-smoke.txt b/evidence/02-smoke.txt new file mode 100644 index 00000000..76c0fbaa --- /dev/null +++ b/evidence/02-smoke.txt @@ -0,0 +1,7 @@ +# 02 публичные проверки (2026-11-12T18:52:39Z) +$ python scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +exit code: 0 +$ python tests/smoke.py --base-url http://localhost:8080 +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. +exit code: 0 diff --git a/evidence/03-student-checks.txt b/evidence/03-student-checks.txt new file mode 100644 index 00000000..7f830827 --- /dev/null +++ b/evidence/03-student-checks.txt @@ -0,0 +1,44 @@ +# 03 собственные проверки (2026-11-12T18:52:41Z) +$ python student-tests/lab2_checks.py --base-url http://localhost:8080 +PASS: повторный username -> 409 +PASS: пароль короче 12 -> 400 +PASS: лишнее поле -> 400 +PASS: User не содержит пароль/hash/токен +PASS: гонка одинакового username: ровно один 201, остальные 409 +PASS: неверный пароль и неизвестный пользователь неразличимы (401, тот же code/message/заголовок) +PASS: вход JSON-телом без Basic -> 401 +PASS: Bearer на POST /auth/sessions -> 401 +PASS: токен >=256 бит, token_type Bearer +PASS: Basic на бизнес-endpoint -> 401 + WWW-Authenticate: Bearer +PASS: один X-User-Id доступа не даёт +PASS: X-User-Id игнорируется: владелец определяется токеном +PASS: неизвестный токен -> 401 +PASS: X-Request-Id совпадает с request_id в теле ошибки +PASS: чат с неизвестным участником -> 400 +PASS: после отказа новый чат не появился (нет частичной записи) +PASS: чат создан с обоими участниками +PASS: создатель обязан быть среди member_ids -> 400 +PASS: посторонний: GET /chat -> 404 +PASS: посторонний: GET /messages -> 404 +PASS: посторонний не может писать -> 404 +PASS: неверный UUID /chats/not-a-uuid -> 400 +PASS: неверный UUID /chats/not-a-uuid/messages -> 400 +PASS: sender_id в запросе не принимается -> 400 +PASS: пробельный текст -> 400 +PASS: отправитель берётся из токена +PASS: пагинация limit=2: без повторов, все 6 сообщений +PASS: cursor от другого чата -> 400 +PASS: ?limit=0 -> 400 +PASS: ?limit=101 -> 400 +PASS: ?limit=abc -> 400 +PASS: ?limit=%2B5 -> 400 +PASS: ?limit=2&limit=3 -> 400 +PASS: тело >1 MiB -> 413 +PASS: не JSON Content-Type -> 415 +PASS: битый JSON -> 400 +PASS: logout -> 204 +PASS: повторный logout с отозванным токеном -> 401 +PASS: отозванный токен -> 401 + WWW-Authenticate: Bearer +PASS: logout одного пользователя не затрагивает чужие сессии +PASS: все проверки режима 'main' +exit code: 0 diff --git a/evidence/04-persistence.txt b/evidence/04-persistence.txt new file mode 100644 index 00000000..331e57f3 --- /dev/null +++ b/evidence/04-persistence.txt @@ -0,0 +1,29 @@ +# 04 сохранность при рестарте API и PostgreSQL (2026-11-12T18:52:43Z) +--- до +/mtusi2026lab2-api-1 StartedAt=2026-11-12T18:08:09.637929997Z RestartCount=0 +/mtusi2026lab2-postgres-1 StartedAt=2026-11-12T18:08:14.311138792Z RestartCount=0 +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab2-api-1 mtusi2026lab2-api "uvicorn app.main:ap…" api 44 minutes ago Up 44 minutes (healthy) 127.0.0.1:8080->8080/tcp +mtusi2026lab2-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 45 minutes ago Up 44 minutes (healthy) 5432/tcp +$ python tests/resilience.py --mode persistence --action-script scripts/restart.cmd +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +exit code: 0 +--- после (StartedAt должен измениться у обоих контейнеров) +/mtusi2026lab2-api-1 StartedAt=2026-11-12T18:52:47.887609866Z RestartCount=0 +/mtusi2026lab2-postgres-1 StartedAt=2026-11-12T18:52:46.134830386Z RestartCount=0 +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab2-api-1 mtusi2026lab2-api "uvicorn app.main:ap…" api 44 minutes ago Up 2 seconds (health: starting) 127.0.0.1:8080->8080/tcp +mtusi2026lab2-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 45 minutes ago Up 3 seconds (healthy) 5432/tcp +--- время восстановления одного рестарта (hook + ожидание /health/ready) + Container mtusi2026lab2-postgres-1 Restarting + Container mtusi2026lab2-postgres-1 Started + Container mtusi2026lab2-api-1 Restarting + Container mtusi2026lab2-api-1 Started +готов через 4 с +--- проверка сохранности данных в БД после рестарта + users | chats | messages | sessions +-------+-------+----------+---------- + 21 | 8 | 18 | 22 +(1 row) + diff --git a/evidence/05-db-schema.txt b/evidence/05-db-schema.txt new file mode 100644 index 00000000..1bd6de00 --- /dev/null +++ b/evidence/05-db-schema.txt @@ -0,0 +1,109 @@ +# 05 схема БД (2026-11-12T18:52:54Z) + version | applied_at +--------------+------------------------------ + 001_init.sql | 2026-11-12 18:07:29.27036+00 +(1 row) + + List of relations + Schema | Name | Type | Owner +--------+-------------------+-------+------- + public | chat_members | table | msg + public | chats | table | msg + public | messages | table | msg + public | schema_migrations | table | msg + public | sessions | table | msg + public | users | table | msg +(6 rows) + + Table "public.users" + Column | Type | Collation | Nullable | Default +---------------+--------------------------+-----------+----------+--------- + id | uuid | | not null | + username | text | | not null | + display_name | text | | not null | + password_hash | text | | not null | + created_at | timestamp with time zone | | not null | now() +Indexes: + "users_pkey" PRIMARY KEY, btree (id) + "users_username_key" UNIQUE CONSTRAINT, btree (username) +Check constraints: + "users_display_name_check" CHECK (char_length(display_name) >= 1 AND char_length(display_name) <= 100) + "users_username_check" CHECK (username ~ '^[a-z0-9_]{3,32}$'::text) +Referenced by: + TABLE "chat_members" CONSTRAINT "chat_members_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) + TABLE "messages" CONSTRAINT "messages_sender_id_fkey" FOREIGN KEY (sender_id) REFERENCES users(id) + TABLE "sessions" CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) + + Table "public.chats" + Column | Type | Collation | Nullable | Default +------------+--------------------------+-----------+----------+------------------- + id | uuid | | not null | + title | text | | not null | + created_at | timestamp with time zone | | not null | clock_timestamp() +Indexes: + "chats_pkey" PRIMARY KEY, btree (id) + "chats_created_idx" btree (created_at, id) +Check constraints: + "chats_title_check" CHECK (char_length(title) >= 1 AND char_length(title) <= 100) +Referenced by: + TABLE "chat_members" CONSTRAINT "chat_members_chat_id_fkey" FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE + TABLE "messages" CONSTRAINT "messages_chat_id_fkey" FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE + + Table "public.chat_members" + Column | Type | Collation | Nullable | Default +---------+------+-----------+----------+--------- + chat_id | uuid | | not null | + user_id | uuid | | not null | +Indexes: + "chat_members_pkey" PRIMARY KEY, btree (chat_id, user_id) + "chat_members_user_idx" btree (user_id, chat_id) +Foreign-key constraints: + "chat_members_chat_id_fkey" FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE + "chat_members_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) + + Table "public.messages" + Column | Type | Collation | Nullable | Default +------------+--------------------------+-----------+----------+------------------- + id | uuid | | not null | + chat_id | uuid | | not null | + sender_id | uuid | | not null | + text | text | | not null | + created_at | timestamp with time zone | | not null | clock_timestamp() +Indexes: + "messages_pkey" PRIMARY KEY, btree (id) + "messages_history_idx" btree (chat_id, created_at, id) +Check constraints: + "messages_text_check" CHECK (char_length(text) >= 1 AND char_length(text) <= 4000) +Foreign-key constraints: + "messages_chat_id_fkey" FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE + "messages_sender_id_fkey" FOREIGN KEY (sender_id) REFERENCES users(id) + + Table "public.sessions" + Column | Type | Collation | Nullable | Default +------------+--------------------------+-----------+----------+--------- + token_hash | bytea | | not null | + user_id | uuid | | not null | + expires_at | timestamp with time zone | | not null | + revoked_at | timestamp with time zone | | | +Indexes: + "sessions_pkey" PRIMARY KEY, btree (token_hash) + "sessions_expires_idx" btree (expires_at) +Foreign-key constraints: + "sessions_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) + +--- пароли хранятся как Argon2id + hash_prefix | count +-------------+------- + $argon2id$ | 21 +(1 row) + +--- в sessions только sha256 токена (32 байта), не сам токен + token_hash_bytes | count +------------------+------- + 32 | 22 +(1 row) + +--- volume с данными PostgreSQL +volume mtusi2026lab2_pgdata -> /var/lib/postgresql/data +bind -> /run/secrets/pg_password + diff --git a/evidence/06-migrations.txt b/evidence/06-migrations.txt new file mode 100644 index 00000000..abbbdb82 --- /dev/null +++ b/evidence/06-migrations.txt @@ -0,0 +1,30 @@ +# 06 повторный запуск миграций (2026-11-12T18:52:58Z) +--- до + version +-------------- + 001_init.sql +(1 row) + + users | messages +-------+---------- + 21 | 18 +(1 row) + +--- рестарт API (миграции выполняются при старте) + Container mtusi2026lab2-api-1 Restarting + Container mtusi2026lab2-api-1 Started +ready +--- ещё два явных запуска migrate.run внутри контейнера api +migrate.run ok +migrate.run ok +--- после + version +-------------- + 001_init.sql +(1 row) + + users | messages +-------+---------- + 21 | 18 +(1 row) + diff --git a/evidence/07-ttl.txt b/evidence/07-ttl.txt new file mode 100644 index 00000000..4ed9c1ba --- /dev/null +++ b/evidence/07-ttl.txt @@ -0,0 +1,23 @@ +# 07 истечение сессии при SESSION_TTL_SECONDS=2 (2026-11-12T18:53:04Z) +$ SESSION_TTL_SECONDS=2 docker compose up -d api + Container mtusi2026lab2-postgres-1 Running + Container mtusi2026lab2-api-1 Recreate + Container mtusi2026lab2-api-1 Recreated + Container mtusi2026lab2-postgres-1 Waiting + Container mtusi2026lab2-postgres-1 Healthy + Container mtusi2026lab2-api-1 Starting + Container mtusi2026lab2-api-1 Started +ready (TTL=2) +PASS: TTL: сразу после входа токен действует (200) +PASS: TTL: через 3.5 с при SESSION_TTL_SECONDS=2 токен истёк (401) +PASS: все проверки режима 'ttl' +exit code: 0 +--- возврат к TTL по умолчанию + Container mtusi2026lab2-postgres-1 Running + Container mtusi2026lab2-api-1 Recreate + Container mtusi2026lab2-api-1 Recreated + Container mtusi2026lab2-postgres-1 Waiting + Container mtusi2026lab2-postgres-1 Healthy + Container mtusi2026lab2-api-1 Starting + Container mtusi2026lab2-api-1 Started +ready (TTL по умолчанию) diff --git a/evidence/08-db-down.txt b/evidence/08-db-down.txt new file mode 100644 index 00000000..b732a2a8 --- /dev/null +++ b/evidence/08-db-down.txt @@ -0,0 +1,14 @@ +# 08 недоступность PostgreSQL (2026-11-12T18:53:15Z) +$ docker compose stop postgres + Container mtusi2026lab2-postgres-1 Stopping + Container mtusi2026lab2-postgres-1 Stopped +GET /health/live -> 200 +GET /health/ready -> {"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"9c380c3a7b7b4c8fa3033cdbf0e35f5b"}} 503 +GET /api/v1/users/me (анонимный токен) -> {"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"ac5c64206e424174a5e3c2d1c1e41eae"}} 503 +$ docker compose start postgres + Container mtusi2026lab2-postgres-1 Starting + Container mtusi2026lab2-postgres-1 Started +ready снова через 2 с (без рестарта API) +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab2-api-1 mtusi2026lab2-api "uvicorn app.main:ap…" api 8 seconds ago Up 6 seconds (healthy) 127.0.0.1:8080->8080/tcp +mtusi2026lab2-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 45 minutes ago Up 1 second (health: starting) 5432/tcp diff --git a/evidence/09-git-hygiene.txt b/evidence/09-git-hygiene.txt new file mode 100644 index 00000000..96c5133b --- /dev/null +++ b/evidence/09-git-hygiene.txt @@ -0,0 +1,7 @@ +# 09 секреты и volumes вне Git (2026-11-12T18:53:20Z) +$ git check-ignore -v secrets/pg_password secrets/database_url .env +.gitignore:35:secrets/ secrets/pg_password +.gitignore:35:secrets/ secrets/database_url +.gitignore:36:.env .env +$ отслеживаемые файлы, похожие на секреты: +нет diff --git a/evidence/summary.txt b/evidence/summary.txt new file mode 100644 index 00000000..2c2d0c6c --- /dev/null +++ b/evidence/summary.txt @@ -0,0 +1,669 @@ +# Сводка сбора доказательств (2026-11-12T18:53:20Z) + +01 окружение -> evidence/01-env.txt +02 smoke -> evidence/02-smoke.txt: 1 PASS-строк smoke +03 собственные -> evidence/03-student-checks.txt: PASS: все проверки режима 'main' +04 persistence -> evidence/04-persistence.txt: PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +05 схема БД -> evidence/05-db-schema.txt +06 миграции повторно -> evidence/06-migrations.txt +07 TTL -> evidence/07-ttl.txt: PASS: все проверки режима 'ttl' +08 БД недоступна -> evidence/08-db-down.txt +09 git hygiene -> evidence/09-git-hygiene.txt + + +=================== evidence/00-clean-start.txt +# 00 чистый старт (2026-11-12T18:04:45Z) +$ docker compose down -v + Volume mtusi2026lab2_pgdata Removing + Volume mtusi2026lab2_pgdata Removed +$ sh scripts/setup-secrets.sh +secrets: ok (значения не печатаются) +$ docker compose up -d --build + postgres Pulling + 500aaa681781 Pulling fs layer + 6886cb0fa181 Pulling fs layer + 09852ea151b6 Pulling fs layer + 3c23ffc3610d Pulling fs layer + da9db072f522 Pulling fs layer + 7c35d0b2112f Pulling fs layer + 754dcd3183db Pulling fs layer + 5b2b0e42c692 Pulling fs layer + d68e4f14dc32 Pulling fs layer + b6fcda863f21 Pulling fs layer + 4f90fd4705e0 Pulling fs layer + 6886cb0fa181 Download complete + 500aaa681781 Download complete + 754dcd3183db Downloading [==================================================>] 5.416kB/5.416kB + b6fcda863f21 Download complete + 7c35d0b2112f Download complete + 5b2b0e42c692 Download complete + 09852ea151b6 Download complete + 4f90fd4705e0 Download complete + 754dcd3183db Download complete + 3c23ffc3610d Download complete + d68e4f14dc32 Downloading [> ] 1.049MB/94.39MB + da9db072f522 Downloading [==============> ] 1.049MB/3.624MB + d68e4f14dc32 Downloading [> ] 1.049MB/94.39MB + da9db072f522 Downloading [==============> ] 1.049MB/3.624MB + d68e4f14dc32 Downloading [> ] 1.049MB/94.39MB + da9db072f522 Downloading [==============> ] 1.049MB/3.624MB + d68e4f14dc32 Downloading [=> ] 2.097MB/94.39MB + d68e4f14dc32 Downloading [=> ] 2.097MB/94.39MB + da9db072f522 Downloading [==============> ] 1.049MB/3.624MB + d68e4f14dc32 Downloading [=> ] 3.146MB/94.39MB + da9db072f522 Downloading [============================> ] 2.097MB/3.624MB + d68e4f14dc32 Downloading [=> ] 3.146MB/94.39MB + da9db072f522 Downloading [===========================================> ] 3.146MB/3.624MB + d68e4f14dc32 Downloading [==> ] 4.194MB/94.39MB + da9db072f522 Download complete + da9db072f522 Extracting 1 s + d68e4f14dc32 Downloading [==> ] 4.194MB/94.39MB + da9db072f522 Extracting 1 s + d68e4f14dc32 Downloading [==> ] 4.194MB/94.39MB + da9db072f522 Pull complete + d68e4f14dc32 Downloading [==> ] 5.243MB/94.39MB + 7c35d0b2112f Extracting 1 s + d68e4f14dc32 Downloading [===> ] 6.291MB/94.39MB + 7c35d0b2112f Pull complete + 3c23ffc3610d Pull complete + d68e4f14dc32 Downloading [===> ] 6.291MB/94.39MB + 6886cb0fa181 Pull complete + 4f90fd4705e0 Pull complete + d68e4f14dc32 Downloading [===> ] 7.34MB/94.39MB + d68e4f14dc32 Downloading [====> ] 8.389MB/94.39MB + d68e4f14dc32 Downloading [====> ] 8.389MB/94.39MB + d68e4f14dc32 Downloading [====> ] 9.437MB/94.39MB + d68e4f14dc32 Downloading [=====> ] 10.49MB/94.39MB + d68e4f14dc32 Downloading [=====> ] 10.49MB/94.39MB + d68e4f14dc32 Downloading [=====> ] 10.49MB/94.39MB + d68e4f14dc32 Downloading [======> ] 11.53MB/94.39MB + d68e4f14dc32 Downloading [======> ] 12.58MB/94.39MB + d68e4f14dc32 Downloading [======> ] 12.58MB/94.39MB + d68e4f14dc32 Downloading [=======> ] 13.63MB/94.39MB + d68e4f14dc32 Downloading [=======> ] 14.02MB/94.39MB + d68e4f14dc32 Downloading [=======> ] 14.68MB/94.39MB + d68e4f14dc32 Downloading [========> ] 15.27MB/94.39MB + d68e4f14dc32 Downloading [========> ] 16.36MB/94.39MB + d68e4f14dc32 Downloading [========> ] 16.78MB/94.39MB + d68e4f14dc32 Downloading [=========> ] 17.83MB/94.39MB + d68e4f14dc32 Downloading [=========> ] 17.83MB/94.39MB + d68e4f14dc32 Downloading [=========> ] 17.83MB/94.39MB + d68e4f14dc32 Downloading [=========> ] 18.87MB/94.39MB + d68e4f14dc32 Downloading [==========> ] 19.92MB/94.39MB + d68e4f14dc32 Downloading [===========> ] 20.97MB/94.39MB + d68e4f14dc32 Downloading [===========> ] 22.02MB/94.39MB + d68e4f14dc32 Downloading [===========> ] 22.02MB/94.39MB + d68e4f14dc32 Downloading [============> ] 23.07MB/94.39MB + d68e4f14dc32 Downloading [============> ] 24.12MB/94.39MB + d68e4f14dc32 Downloading [=============> ] 25.17MB/94.39MB + d68e4f14dc32 Downloading [=============> ] 26.21MB/94.39MB + d68e4f14dc32 Downloading [=============> ] 26.21MB/94.39MB + d68e4f14dc32 Downloading [==============> ] 27.26MB/94.39MB + d68e4f14dc32 Downloading [===============> ] 29.36MB/94.39MB + d68e4f14dc32 Downloading [===============> ] 29.36MB/94.39MB + d68e4f14dc32 Downloading [================> ] 30.41MB/94.39MB + d68e4f14dc32 Downloading [================> ] 31.46MB/94.39MB + d68e4f14dc32 Downloading [=================> ] 32.51MB/94.39MB + d68e4f14dc32 Downloading [=================> ] 33.55MB/94.39MB + d68e4f14dc32 Downloading [=================> ] 33.55MB/94.39MB + d68e4f14dc32 Downloading [==================> ] 34.6MB/94.39MB + d68e4f14dc32 Downloading [==================> ] 35.65MB/94.39MB + d68e4f14dc32 Downloading [===================> ] 37.75MB/94.39MB + d68e4f14dc32 Downloading [====================> ] 38.8MB/94.39MB + d68e4f14dc32 Downloading [=====================> ] 39.85MB/94.39MB + d68e4f14dc32 Downloading [=====================> ] 39.85MB/94.39MB + d68e4f14dc32 Downloading [======================> ] 41.94MB/94.39MB + d68e4f14dc32 Downloading [======================> ] 42.99MB/94.39MB + d68e4f14dc32 Downloading [======================> ] 42.99MB/94.39MB + d68e4f14dc32 Downloading [=======================> ] 45.09MB/94.39MB + d68e4f14dc32 Downloading [=======================> ] 45.09MB/94.39MB + d68e4f14dc32 Downloading [========================> ] 45.65MB/94.39MB + d68e4f14dc32 Downloading [========================> ] 47.19MB/94.39MB + d68e4f14dc32 Downloading [==========================> ] 49.28MB/94.39MB + d68e4f14dc32 Downloading [==========================> ] 50.33MB/94.39MB + d68e4f14dc32 Downloading [==========================> ] 50.33MB/94.39MB + d68e4f14dc32 Downloading [===========================> ] 52.43MB/94.39MB + d68e4f14dc32 Downloading [============================> ] 53.48MB/94.39MB + d68e4f14dc32 Downloading [============================> ] 54.53MB/94.39MB + d68e4f14dc32 Downloading [=============================> ] 55.57MB/94.39MB + d68e4f14dc32 Downloading [=============================> ] 56.62MB/94.39MB + d68e4f14dc32 Downloading [=============================> ] 56.62MB/94.39MB + d68e4f14dc32 Downloading [==============================> ] 57.67MB/94.39MB + d68e4f14dc32 Downloading [===============================> ] 59.77MB/94.39MB + d68e4f14dc32 Downloading [================================> ] 60.82MB/94.39MB + d68e4f14dc32 Downloading [================================> ] 61.87MB/94.39MB + d68e4f14dc32 Downloading [=================================> ] 62.91MB/94.39MB + d68e4f14dc32 Downloading [=================================> ] 63.96MB/94.39MB + d68e4f14dc32 Downloading [==================================> ] 65.01MB/94.39MB + d68e4f14dc32 Downloading [==================================> ] 66.06MB/94.39MB + d68e4f14dc32 Downloading [==================================> ] 66.06MB/94.39MB + d68e4f14dc32 Downloading [===================================> ] 67.11MB/94.39MB + d68e4f14dc32 Downloading [====================================> ] 68.16MB/94.39MB + d68e4f14dc32 Downloading [====================================> ] 69.21MB/94.39MB + d68e4f14dc32 Downloading [=====================================> ] 71.27MB/94.39MB + d68e4f14dc32 Downloading [======================================> ] 72.35MB/94.39MB + d68e4f14dc32 Downloading [======================================> ] 73.4MB/94.39MB + d68e4f14dc32 Downloading [=======================================> ] 74.45MB/94.39MB + d68e4f14dc32 Downloading [=======================================> ] 75.5MB/94.39MB + d68e4f14dc32 Downloading [=======================================> ] 75.5MB/94.39MB + d68e4f14dc32 Downloading [========================================> ] 76.55MB/94.39MB + d68e4f14dc32 Downloading [=========================================> ] 77.59MB/94.39MB + d68e4f14dc32 Downloading [==========================================> ] 79.69MB/94.39MB + d68e4f14dc32 Downloading [==========================================> ] 80.74MB/94.39MB + d68e4f14dc32 Downloading [===========================================> ] 81.79MB/94.39MB + d68e4f14dc32 Downloading [===========================================> ] 82.84MB/94.39MB + d68e4f14dc32 Downloading [============================================> ] 83.54MB/94.39MB + d68e4f14dc32 Downloading [============================================> ] 84.93MB/94.39MB + d68e4f14dc32 Downloading [============================================> ] 84.93MB/94.39MB + d68e4f14dc32 Downloading [=============================================> ] 85.98MB/94.39MB + d68e4f14dc32 Downloading [=============================================> ] 85.98MB/94.39MB + d68e4f14dc32 Downloading [=============================================> ] 85.98MB/94.39MB + d68e4f14dc32 Downloading [==============================================> ] 88.08MB/94.39MB + d68e4f14dc32 Downloading [==============================================> ] 88.08MB/94.39MB + d68e4f14dc32 Downloading [===============================================> ] 89.13MB/94.39MB + d68e4f14dc32 Downloading [================================================> ] 91.23MB/94.39MB + d68e4f14dc32 Downloading [================================================> ] 91.23MB/94.39MB + d68e4f14dc32 Downloading [================================================> ] 92.27MB/94.39MB + d68e4f14dc32 Downloading [================================================> ] 92.27MB/94.39MB + d68e4f14dc32 Downloading [================================================> ] 92.27MB/94.39MB + d68e4f14dc32 Downloading [==================================================>] 94.39MB/94.39MB + d68e4f14dc32 Downloading [==================================================>] 94.39MB/94.39MB + d68e4f14dc32 Downloading [==================================================>] 94.39MB/94.39MB + d68e4f14dc32 Download complete + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 1 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 2 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 3 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 4 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + d68e4f14dc32 Extracting 5 s + b6fcda863f21 Pull complete + 5b2b0e42c692 Pull complete + d68e4f14dc32 Pull complete + 500aaa681781 Pull complete + 09852ea151b6 Pull complete + 754dcd3183db Pull complete + postgres Pulled +Compose can now delegate builds to bake for better performance. + To do so, set COMPOSE_BAKE=true. +#0 building with "desktop-linux" instance using docker driver + +#1 [api internal] load build definition from Dockerfile +#1 transferring dockerfile: 500B 0.0s done +#1 DONE 0.1s + +#2 [api internal] load metadata for docker.io/library/python:3.12.7-slim-bookworm +#2 DONE 3.0s + +#3 [api internal] load .dockerignore +#3 transferring context: 216B done +#3 DONE 0.0s + +#4 [api internal] load build context +#4 DONE 0.0s + +#5 [api 1/6] FROM docker.io/library/python:3.12.7-slim-bookworm@sha256:60d9996b6a8a3689d36db740b49f4327be3be09a21122bd02fb8895abb38b50d +#5 resolve docker.io/library/python:3.12.7-slim-bookworm@sha256:60d9996b6a8a3689d36db740b49f4327be3be09a21122bd02fb8895abb38b50d 0.0s done +#5 DONE 0.0s + +#5 [api 1/6] FROM docker.io/library/python:3.12.7-slim-bookworm@sha256:60d9996b6a8a3689d36db740b49f4327be3be09a21122bd02fb8895abb38b50d +#5 CACHED + +#4 [api internal] load build context +#4 transferring context: 18.27kB 0.0s done +#4 DONE 0.1s + +#6 [api 2/6] WORKDIR /app +#6 DONE 0.3s + +#7 [api 3/6] COPY src/requirements.txt . +#7 DONE 0.0s + +#8 [api 4/6] RUN pip install --no-cache-dir -r requirements.txt +#8 3.470 Collecting starlette==0.41.3 (from -r requirements.txt (line 1)) +#8 4.000 Downloading starlette-0.41.3-py3-none-any.whl.metadata (6.0 kB) +#8 4.333 Collecting uvicorn==0.32.1 (from -r requirements.txt (line 2)) +#8 4.440 Downloading uvicorn-0.32.1-py3-none-any.whl.metadata (6.6 kB) +#8 4.634 Collecting psycopg==3.2.3 (from psycopg[binary,pool]==3.2.3->-r requirements.txt (line 3)) +#8 4.740 Downloading psycopg-3.2.3-py3-none-any.whl.metadata (4.3 kB) +#8 5.137 Collecting argon2-cffi==23.1.0 (from -r requirements.txt (line 4)) +#8 5.244 Downloading argon2_cffi-23.1.0-py3-none-any.whl.metadata (5.2 kB) +#8 5.540 Collecting anyio<5,>=3.4.0 (from starlette==0.41.3->-r requirements.txt (line 1)) +#8 5.647 Downloading anyio-4.16.0-py3-none-any.whl.metadata (4.7 kB) +#8 5.977 Collecting click>=7.0 (from uvicorn==0.32.1->-r requirements.txt (line 2)) +#8 6.083 Downloading click-8.5.1-py3-none-any.whl.metadata (2.6 kB) +#8 6.575 Collecting h11>=0.8 (from uvicorn==0.32.1->-r requirements.txt (line 2)) +#8 6.682 Downloading h11-0.16.0-py3-none-any.whl.metadata (8.3 kB) +#8 7.089 Collecting typing-extensions>=4.6 (from psycopg==3.2.3->psycopg[binary,pool]==3.2.3->-r requirements.txt (line 3)) +#8 7.197 Downloading typing_extensions-4.16.0-py3-none-any.whl.metadata (3.3 kB) +#8 7.436 Collecting argon2-cffi-bindings (from argon2-cffi==23.1.0->-r requirements.txt (line 4)) +#8 7.542 Downloading argon2_cffi_bindings-26.1.0-cp310-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl.metadata (7.5 kB) +#8 12.83 Collecting psycopg-binary==3.2.3 (from psycopg[binary,pool]==3.2.3->-r requirements.txt (line 3)) +#8 12.94 Downloading psycopg_binary-3.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (2.8 kB) +#8 13.22 Collecting psycopg-pool (from psycopg[binary,pool]==3.2.3->-r requirements.txt (line 3)) +#8 13.33 Downloading psycopg_pool-3.3.3-py3-none-any.whl.metadata (2.8 kB) +#8 13.63 Collecting idna>=2.8 (from anyio<5,>=3.4.0->starlette==0.41.3->-r requirements.txt (line 1)) +#8 13.73 Downloading idna-3.20-py3-none-any.whl.metadata (7.2 kB) +#8 17.93 Collecting cffi>=1.0.1 (from argon2-cffi-bindings->argon2-cffi==23.1.0->-r requirements.txt (line 4)) +#8 18.50 Downloading cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (2.5 kB) +#8 18.65 Collecting pycparser (from cffi>=1.0.1->argon2-cffi-bindings->argon2-cffi==23.1.0->-r requirements.txt (line 4)) +#8 18.76 Downloading pycparser-3.12-py3-none-any.whl.metadata (9.7 kB) +#8 18.95 Downloading starlette-0.41.3-py3-none-any.whl (73 kB) +#8 19.71 Downloading uvicorn-0.32.1-py3-none-any.whl (63 kB) +#8 20.39 Downloading psycopg-3.2.3-py3-none-any.whl (197 kB) +#8 24.93 Downloading argon2_cffi-23.1.0-py3-none-any.whl (15 kB) +#8 25.35 Downloading psycopg_binary-3.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.2 MB) +#8 114.8 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.2/4.2 MB 48.1 kB/s eta 0:00:00 +#8 114.9 Downloading anyio-4.16.0-py3-none-any.whl (134 kB) +#8 116.6 Downloading click-8.5.1-py3-none-any.whl (126 kB) +#8 118.1 Downloading h11-0.16.0-py3-none-any.whl (37 kB) +#8 118.5 Downloading typing_extensions-4.16.0-py3-none-any.whl (45 kB) +#8 119.0 Downloading argon2_cffi_bindings-26.1.0-cp310-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl (26 kB) +#8 119.3 Downloading psycopg_pool-3.3.3-py3-none-any.whl (40 kB) +#8 119.9 Downloading cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (221 kB) +#8 123.5 Downloading idna-3.20-py3-none-any.whl (69 kB) +#8 124.3 Downloading pycparser-3.12-py3-none-any.whl (62 kB) +#8 125.4 Installing collected packages: typing-extensions, pycparser, psycopg-binary, idna, h11, click, uvicorn, psycopg-pool, psycopg, cffi, anyio, starlette, argon2-cffi-bindings, argon2-cffi +#8 126.4 Successfully installed anyio-4.16.0 argon2-cffi-23.1.0 argon2-cffi-bindings-26.1.0 cffi-2.1.1 click-8.5.1 h11-0.16.0 idna-3.20 psycopg-3.2.3 psycopg-binary-3.2.3 psycopg-pool-3.3.3 pycparser-3.12 starlette-0.41.3 typing-extensions-4.16.0 uvicorn-0.32.1 +#8 126.4 WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable.It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning. +#8 126.9 +#8 126.9 [notice] A new release of pip is available: 24.2 -> 26.3 +#8 126.9 [notice] To update, run: pip install --upgrade pip +#8 DONE 127.2s + +#9 [api 5/6] COPY src/ . +#9 DONE 0.1s + +#10 [api 6/6] RUN useradd -r -u 10001 appuser +#10 0.477 useradd warning: appuser's uid 10001 is greater than SYS_UID_MAX 999 +#10 DONE 0.5s + +#11 [api] exporting to image +#11 exporting layers +#11 exporting layers 0.9s done +#11 exporting manifest sha256:2e1cc496adb1045607f08bb61ac4f573f784e82fdf62ec3d61e7baaa95bffcc9 0.0s done +#11 exporting config sha256:23ae9e77c4d2fee678bf455531777f07f6d77a0c928ab9092130325030805f1c 0.0s done +#11 exporting attestation manifest sha256:f9af64a0e5f7d2e5fbe8d182bb92bcac260b5cd1b64ddb99ea6be12c6d80a3fb 0.0s done +#11 exporting manifest list sha256:bf04714d16cb9b11addf8ab71caa4754875e7b55ffb419aff89f2e77a63b4248 0.0s done +#11 naming to docker.io/library/mtusi2026lab2-api:latest done +#11 unpacking to docker.io/library/mtusi2026lab2-api:latest +#11 unpacking to docker.io/library/mtusi2026lab2-api:latest 0.4s done +#11 DONE 1.4s + +#12 [api] resolving provenance for metadata file +#12 DONE 0.0s + api Built + Network mtusi2026lab2_default Creating + Network mtusi2026lab2_default Created + Volume "mtusi2026lab2_pgdata" Creating + Volume "mtusi2026lab2_pgdata" Created + Container mtusi2026lab2-postgres-1 Creating + Container mtusi2026lab2-postgres-1 Created + Container mtusi2026lab2-api-1 Creating + Container mtusi2026lab2-api-1 Created + Container mtusi2026lab2-postgres-1 Starting + Container mtusi2026lab2-postgres-1 Started + Container mtusi2026lab2-postgres-1 Waiting + Container mtusi2026lab2-postgres-1 Healthy + Container mtusi2026lab2-api-1 Starting + Container mtusi2026lab2-api-1 Started +ready через 164 с после запуска up + +=================== evidence/01-env.txt +# 01 окружение (2026-11-12T18:52:34Z) +commit: ac54d4cfde5fa2876fdfedf55fd7d5840c33cdac +git status: +?? evidence/00-clean-start.txt +?? evidence/01-env.txt +?? evidence/02-smoke.txt +?? evidence/03-student-checks.txt +?? evidence/04-persistence.txt +?? evidence/05-db-schema.txt +?? evidence/06-migrations.txt +?? evidence/07-ttl.txt +?? evidence/08-db-down.txt +?? evidence/09-git-hygiene.txt +?? evidence/summary.txt +$ docker version +client=28.0.4 server=28.0.4 os=linux/amd64 +$ docker compose version +Docker Compose version v2.34.0-desktop.1 +python: Python 3.11.5 +$ docker compose config --quiet +compose config: OK +$ docker compose images +CONTAINER REPOSITORY TAG IMAGE ID SIZE +mtusi2026lab2-api-1 mtusi2026lab2-api latest bf04714d16cb 52.1MB +mtusi2026lab2-postgres-1 postgres 16.4-alpine 5660c2cbfea5 99.2MB +$ docker compose ps +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab2-api-1 mtusi2026lab2-api "uvicorn app.main:ap…" api 44 minutes ago Up 44 minutes (healthy) 127.0.0.1:8080->8080/tcp +mtusi2026lab2-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 45 minutes ago Up 44 minutes (healthy) 5432/tcp +$ docker volume ls (pgdata) +local mtusi2026lab2_pgdata +$ docker stats --no-stream +NAME CPU % MEM USAGE / LIMIT +mtusi2026lab2-api-1 0.16% 35.07MiB / 7.694GiB +mtusi2026lab2-postgres-1 0.00% 22.8MiB / 7.694GiB +$ docker info (лимиты хоста) +CPUs=16 Mem=8261029888 + +=================== evidence/02-smoke.txt +# 02 публичные проверки (2026-11-12T18:52:39Z) +$ python scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +exit code: 0 +$ python tests/smoke.py --base-url http://localhost:8080 +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. +exit code: 0 + +=================== evidence/03-student-checks.txt +# 03 собственные проверки (2026-11-12T18:52:41Z) +$ python student-tests/lab2_checks.py --base-url http://localhost:8080 +PASS: повторный username -> 409 +PASS: пароль короче 12 -> 400 +PASS: лишнее поле -> 400 +PASS: User не содержит пароль/hash/токен +PASS: гонка одинакового username: ровно один 201, остальные 409 +PASS: неверный пароль и неизвестный пользователь неразличимы (401, тот же code/message/заголовок) +PASS: вход JSON-телом без Basic -> 401 +PASS: Bearer на POST /auth/sessions -> 401 +PASS: токен >=256 бит, token_type Bearer +PASS: Basic на бизнес-endpoint -> 401 + WWW-Authenticate: Bearer +PASS: один X-User-Id доступа не даёт +PASS: X-User-Id игнорируется: владелец определяется токеном +PASS: неизвестный токен -> 401 +PASS: X-Request-Id совпадает с request_id в теле ошибки +PASS: чат с неизвестным участником -> 400 +PASS: после отказа новый чат не появился (нет частичной записи) +PASS: чат создан с обоими участниками +PASS: создатель обязан быть среди member_ids -> 400 +PASS: посторонний: GET /chat -> 404 +PASS: посторонний: GET /messages -> 404 +PASS: посторонний не может писать -> 404 +PASS: неверный UUID /chats/not-a-uuid -> 400 +PASS: неверный UUID /chats/not-a-uuid/messages -> 400 +PASS: sender_id в запросе не принимается -> 400 +PASS: пробельный текст -> 400 +PASS: отправитель берётся из токена +PASS: пагинация limit=2: без повторов, все 6 сообщений +PASS: cursor от другого чата -> 400 +PASS: ?limit=0 -> 400 +PASS: ?limit=101 -> 400 +PASS: ?limit=abc -> 400 +PASS: ?limit=%2B5 -> 400 +PASS: ?limit=2&limit=3 -> 400 +PASS: тело >1 MiB -> 413 +PASS: не JSON Content-Type -> 415 +PASS: битый JSON -> 400 +PASS: logout -> 204 +PASS: повторный logout с отозванным токеном -> 401 +PASS: отозванный токен -> 401 + WWW-Authenticate: Bearer +PASS: logout одного пользователя не затрагивает чужие сессии +PASS: все проверки режима 'main' +exit code: 0 + +=================== evidence/04-persistence.txt +# 04 сохранность при рестарте API и PostgreSQL (2026-11-12T18:52:43Z) +--- до +/mtusi2026lab2-api-1 StartedAt=2026-11-12T18:08:09.637929997Z RestartCount=0 +/mtusi2026lab2-postgres-1 StartedAt=2026-11-12T18:08:14.311138792Z RestartCount=0 +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab2-api-1 mtusi2026lab2-api "uvicorn app.main:ap…" api 44 minutes ago Up 44 minutes (healthy) 127.0.0.1:8080->8080/tcp +mtusi2026lab2-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 45 minutes ago Up 44 minutes (healthy) 5432/tcp +$ python tests/resilience.py --mode persistence --action-script scripts/restart.cmd +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +exit code: 0 +--- после (StartedAt должен измениться у обоих контейнеров) +/mtusi2026lab2-api-1 StartedAt=2026-11-12T18:52:47.887609866Z RestartCount=0 +/mtusi2026lab2-postgres-1 StartedAt=2026-11-12T18:52:46.134830386Z RestartCount=0 +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab2-api-1 mtusi2026lab2-api "uvicorn app.main:ap…" api 44 minutes ago Up 2 seconds (health: starting) 127.0.0.1:8080->8080/tcp +mtusi2026lab2-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 45 minutes ago Up 3 seconds (healthy) 5432/tcp +--- время восстановления одного рестарта (hook + ожидание /health/ready) + Container mtusi2026lab2-postgres-1 Restarting + Container mtusi2026lab2-postgres-1 Started + Container mtusi2026lab2-api-1 Restarting + Container mtusi2026lab2-api-1 Started +готов через 4 с +--- проверка сохранности данных в БД после рестарта + users | chats | messages | sessions +-------+-------+----------+---------- + 21 | 8 | 18 | 22 +(1 row) + + +=================== evidence/05-db-schema.txt +# 05 схема БД (2026-11-12T18:52:54Z) + version | applied_at +--------------+------------------------------ + 001_init.sql | 2026-11-12 18:07:29.27036+00 +(1 row) + + List of relations + Schema | Name | Type | Owner +--------+-------------------+-------+------- + public | chat_members | table | msg + public | chats | table | msg + public | messages | table | msg + public | schema_migrations | table | msg + public | sessions | table | msg + public | users | table | msg +(6 rows) + + Table "public.users" + Column | Type | Collation | Nullable | Default +---------------+--------------------------+-----------+----------+--------- + id | uuid | | not null | + username | text | | not null | + display_name | text | | not null | + password_hash | text | | not null | + created_at | timestamp with time zone | | not null | now() +Indexes: + "users_pkey" PRIMARY KEY, btree (id) + "users_username_key" UNIQUE CONSTRAINT, btree (username) +Check constraints: + "users_display_name_check" CHECK (char_length(display_name) >= 1 AND char_length(display_name) <= 100) + "users_username_check" CHECK (username ~ '^[a-z0-9_]{3,32}$'::text) +Referenced by: + TABLE "chat_members" CONSTRAINT "chat_members_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) + TABLE "messages" CONSTRAINT "messages_sender_id_fkey" FOREIGN KEY (sender_id) REFERENCES users(id) + TABLE "sessions" CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) + + Table "public.chats" + Column | Type | Collation | Nullable | Default +------------+--------------------------+-----------+----------+------------------- + id | uuid | | not null | + title | text | | not null | + created_at | timestamp with time zone | | not null | clock_timestamp() +Indexes: + "chats_pkey" PRIMARY KEY, btree (id) + "chats_created_idx" btree (created_at, id) +Check constraints: + "chats_title_check" CHECK (char_length(title) >= 1 AND char_length(title) <= 100) +Referenced by: + TABLE "chat_members" CONSTRAINT "chat_members_chat_id_fkey" FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE + TABLE "messages" CONSTRAINT "messages_chat_id_fkey" FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE + + Table "public.chat_members" + Column | Type | Collation | Nullable | Default +---------+------+-----------+----------+--------- + chat_id | uuid | | not null | + user_id | uuid | | not null | +Indexes: + "chat_members_pkey" PRIMARY KEY, btree (chat_id, user_id) + "chat_members_user_idx" btree (user_id, chat_id) +Foreign-key constraints: + "chat_members_chat_id_fkey" FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE + "chat_members_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) + + Table "public.messages" + Column | Type | Collation | Nullable | Default +------------+--------------------------+-----------+----------+------------------- + id | uuid | | not null | + chat_id | uuid | | not null | + sender_id | uuid | | not null | + text | text | | not null | + created_at | timestamp with time zone | | not null | clock_timestamp() +Indexes: + "messages_pkey" PRIMARY KEY, btree (id) + "messages_history_idx" btree (chat_id, created_at, id) +Check constraints: + "messages_text_check" CHECK (char_length(text) >= 1 AND char_length(text) <= 4000) +Foreign-key constraints: + "messages_chat_id_fkey" FOREIGN KEY (chat_id) REFERENCES chats(id) ON DELETE CASCADE + "messages_sender_id_fkey" FOREIGN KEY (sender_id) REFERENCES users(id) + + Table "public.sessions" + Column | Type | Collation | Nullable | Default +------------+--------------------------+-----------+----------+--------- + token_hash | bytea | | not null | + user_id | uuid | | not null | + expires_at | timestamp with time zone | | not null | + revoked_at | timestamp with time zone | | | +Indexes: + "sessions_pkey" PRIMARY KEY, btree (token_hash) + "sessions_expires_idx" btree (expires_at) +Foreign-key constraints: + "sessions_user_id_fkey" FOREIGN KEY (user_id) REFERENCES users(id) + +--- пароли хранятся как Argon2id + hash_prefix | count +-------------+------- + $argon2id$ | 21 +(1 row) + +--- в sessions только sha256 токена (32 байта), не сам токен + token_hash_bytes | count +------------------+------- + 32 | 22 +(1 row) + +--- volume с данными PostgreSQL +volume mtusi2026lab2_pgdata -> /var/lib/postgresql/data +bind -> /run/secrets/pg_password + + +=================== evidence/06-migrations.txt +# 06 повторный запуск миграций (2026-11-12T18:52:58Z) +--- до + version +-------------- + 001_init.sql +(1 row) + + users | messages +-------+---------- + 21 | 18 +(1 row) + +--- рестарт API (миграции выполняются при старте) + Container mtusi2026lab2-api-1 Restarting + Container mtusi2026lab2-api-1 Started +ready +--- ещё два явных запуска migrate.run внутри контейнера api +migrate.run ok +migrate.run ok +--- после + version +-------------- + 001_init.sql +(1 row) + + users | messages +-------+---------- + 21 | 18 +(1 row) + + +=================== evidence/07-ttl.txt +# 07 истечение сессии при SESSION_TTL_SECONDS=2 (2026-11-12T18:53:04Z) +$ SESSION_TTL_SECONDS=2 docker compose up -d api + Container mtusi2026lab2-postgres-1 Running + Container mtusi2026lab2-api-1 Recreate + Container mtusi2026lab2-api-1 Recreated + Container mtusi2026lab2-postgres-1 Waiting + Container mtusi2026lab2-postgres-1 Healthy + Container mtusi2026lab2-api-1 Starting + Container mtusi2026lab2-api-1 Started +ready (TTL=2) +PASS: TTL: сразу после входа токен действует (200) +PASS: TTL: через 3.5 с при SESSION_TTL_SECONDS=2 токен истёк (401) +PASS: все проверки режима 'ttl' +exit code: 0 +--- возврат к TTL по умолчанию + Container mtusi2026lab2-postgres-1 Running + Container mtusi2026lab2-api-1 Recreate + Container mtusi2026lab2-api-1 Recreated + Container mtusi2026lab2-postgres-1 Waiting + Container mtusi2026lab2-postgres-1 Healthy + Container mtusi2026lab2-api-1 Starting + Container mtusi2026lab2-api-1 Started +ready (TTL по умолчанию) + +=================== evidence/08-db-down.txt +# 08 недоступность PostgreSQL (2026-11-12T18:53:15Z) +$ docker compose stop postgres + Container mtusi2026lab2-postgres-1 Stopping + Container mtusi2026lab2-postgres-1 Stopped +GET /health/live -> 200 +GET /health/ready -> {"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"9c380c3a7b7b4c8fa3033cdbf0e35f5b"}} 503 +GET /api/v1/users/me (анонимный токен) -> {"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"ac5c64206e424174a5e3c2d1c1e41eae"}} 503 +$ docker compose start postgres + Container mtusi2026lab2-postgres-1 Starting + Container mtusi2026lab2-postgres-1 Started +ready снова через 2 с (без рестарта API) +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab2-api-1 mtusi2026lab2-api "uvicorn app.main:ap…" api 8 seconds ago Up 6 seconds (healthy) 127.0.0.1:8080->8080/tcp +mtusi2026lab2-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 45 minutes ago Up 1 second (health: starting) 5432/tcp + +=================== evidence/09-git-hygiene.txt +# 09 секреты и volumes вне Git (2026-11-12T18:53:20Z) +$ git check-ignore -v secrets/pg_password secrets/database_url .env +.gitignore:35:secrets/ secrets/pg_password +.gitignore:35:secrets/ secrets/database_url +.gitignore:36:.env .env +$ отслеживаемые файлы, похожие на секреты: +нет -- 2.54.0