Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8c4d50113 | ||
|
|
ca84823281 | ||
|
|
ff7296c240 |
+5
-10
@@ -1,11 +1,6 @@
|
|||||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
# Copy to .env and choose your own LOCAL synthetic passwords. Do not commit .env.
|
||||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
POSTGRES_USER=lab2
|
||||||
APP_HOST=0.0.0.0
|
POSTGRES_PASSWORD=
|
||||||
APP_PORT=8080
|
POSTGRES_DB=messenger
|
||||||
APP_ENV=lab
|
|
||||||
SESSION_TTL_SECONDS=3600
|
SESSION_TTL_SECONDS=3600
|
||||||
# Choose credentials locally. File paths contain no secret values.
|
LAB2_HOST_PORT=8080
|
||||||
DATABASE_URL_FILE=/run/secrets/database_url
|
|
||||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
|
||||||
SESSION_STORE=postgres
|
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
*.sh text eol=lf
|
||||||
|
*.py text eol=lf
|
||||||
|
*.sql text eol=lf
|
||||||
|
*.cmd text eol=crlf
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
name: Lab 2 application
|
||||||
|
|
||||||
|
on: [push, pull_request]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
postgres:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.12'
|
||||||
|
- name: Build and start
|
||||||
|
run: |
|
||||||
|
python - <<'PY'
|
||||||
|
from pathlib import Path
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
settings = Path(".env.example").read_text()
|
||||||
|
Path(".env").write_text(settings.replace("POSTGRES_PASSWORD=", "POSTGRES_PASSWORD=" + secrets.token_hex(24)))
|
||||||
|
PY
|
||||||
|
docker compose --env-file .env up -d --build --wait --wait-timeout 60
|
||||||
|
- name: Verify API and persistence
|
||||||
|
run: |
|
||||||
|
make test PYTHON=python
|
||||||
|
python tests/student_tests.py
|
||||||
|
python tests/contract_edge_tests.py
|
||||||
|
chmod +x scripts/restart.sh
|
||||||
|
make test-persistence PYTHON=python ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
- name: Stop lab services
|
||||||
|
if: always()
|
||||||
|
run: |
|
||||||
|
if [ -f .env ]; then
|
||||||
|
docker compose --env-file .env down
|
||||||
|
fi
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
FROM python:3.12.10-slim-bookworm
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 APP_HOST=0.0.0.0 APP_PORT=8080
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
COPY app/ ./app/
|
||||||
|
COPY migrations/ ./migrations/
|
||||||
|
EXPOSE 8080
|
||||||
|
CMD ["python", "-m", "app.main"]
|
||||||
@@ -1,37 +1,90 @@
|
|||||||
# Отчёт — лабораторная 2
|
# Лабораторная работа №2. PostgreSQL и сессии
|
||||||
|
|
||||||
- Автор, группа: TODO
|
**Сабитов Бронислав Александрович, БВТ-2302**
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
Дисциплина «Высоконагруженные приложения»
|
||||||
- Commit/PR: TODO после публикации
|
Целевая оценка «3»
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
Запрос на слияние — https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2/pulls/193
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Архитектура
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
HTTP-клиент → FastAPI/Uvicorn → PostgreSQL. Один процесс API обслуживает запросы. PostgreSQL хранит все данные, включая сессии, в именованном томе pgdata.
|
||||||
|
|
||||||
## Архитектура и решения
|
Из ЛР №1 перенесены создание пользователей, чатов и сообщений, проверка членства, формат ошибок с X-Request-Id и пагинация по (created_at, id). В ЛР №2 регистрация принимает пароль, вход выполняется через Basic, защищённые маршруты используют Bearer.
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
| Таблица | Назначение и ограничения |
|
||||||
|
| --- | --- |
|
||||||
|
| users | UUID, уникальный username, отображаемое имя и хеш Argon2id |
|
||||||
|
| chats и chat_members | Чаты и их участники. Составной ключ (chat_id, user_id) исключает повтор участника. Внешние ключи связывают участников с существующими чатами и пользователями |
|
||||||
|
| messages | Сообщения с внешними ключами на чат и отправителя. Индекс (chat_id, created_at, id) соответствует запросу страниц истории |
|
||||||
|
| sessions | Дайджест Bearer-токена, UUID пользователя, время создания и истечения |
|
||||||
|
| schema_migrations | Номера применённых миграций |
|
||||||
|
|
||||||
## Доказательства критериев
|
Чат и весь список участников записываются одной транзакцией. Сообщение возвращается клиенту после COMMIT. Уникальность username гарантирует PostgreSQL, в том числе при одновременной регистрации. Миграция 001 применяется автоматически при старте API в транзакции с блокировкой. При повторном запуске API проверяет существующую версию схемы.
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
При регистрации Argon2id вычисляет хеш с отдельной солью для каждого пароля. Успешный вход генерирует случайный токен из 48 байт и сохраняет в БД его SHA-256-дайджест. Срок действия сессии по умолчанию 3600 секунд. Logout удаляет текущую сессию. После рестарта срок действия уже выданной сессии сохраняется.
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
## Запуск в Windows
|
||||||
|
|
||||||
## Эксперименты и отказы
|
Нужны Docker Desktop с Compose v2.20+ и Python 3.9+ для тестов. В контейнерах закреплены Python 3.12.10 и PostgreSQL 16.16.
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Откройте PowerShell в корне чистого клона или распакованной папки.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
$env:COMPOSE_PROJECT_NAME = "mtusi-lab2-selfcheck-$(Get-Date -Format yyyyMMddHHmmss)"
|
||||||
| --- | --- | --- | --- |
|
$env:LAB2_HOST_PORT = '8082'
|
||||||
| TODO | TODO | TODO | TODO |
|
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\verify-windows.ps1 -Port 8082
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
Эти команды использовались для самостоятельного прогона 30 ноября. Имя COMPOSE_PROJECT_NAME создаёт отдельный стенд со своим томом базы. При первом запуске сценарий создаёт локальный .env со случайным паролем БД. Порт 8082 позволяет держать стенд ЛР №1 на 8080. Аргумент -Port задаёт порт для текущего прогона. Чтобы закрепить другой порт для последующих запусков, измените LAB2_HOST_PORT в .env. Пароль из .env должен соответствовать уже созданному тому PostgreSQL.
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
Сценарий проверяет конфигурацию Compose, собирает и запускает сервисы api и db, ждёт их готовности, выполняет проверки структуры, API и сохранности. Скрипт записывает вывод, время запуска обоих контейнеров до и после рестарта, имя тома и итог проверки миграции в [evidence/results-docker.txt](evidence/results-docker.txt). Адрес проверки готовности при порте 8082 — http://127.0.0.1:8082/health/ready.
|
||||||
|
|
||||||
|
Переменные POSTGRES_USER, POSTGRES_PASSWORD и POSTGRES_DB используются обоими сервисами. У API есть APP_HOST, APP_PORT и SESSION_TTL_SECONDS. PostgreSQL доступен по имени db внутри сети Compose. На хост публикуется только API на 127.0.0.1. .env и данные тома исключены из Git.
|
||||||
|
|
||||||
|
### Альтернативный запуск с GNU Make
|
||||||
|
|
||||||
|
Ниже приведён альтернативный способ повторить проверки. Основной прогон 30 ноября выполнен через PowerShell-скрипт. Он сам вызвал tests/smoke.py, tests/student_tests.py, tests/contract_edge_tests.py и tests/resilience.py. Их команды и результаты записаны в evidence/results-docker.txt. Для примеров GNU Make ниже используется порт 8082.
|
||||||
|
|
||||||
|
chmod +x scripts/restart.sh
|
||||||
|
make check
|
||||||
|
make test BASE_URL=http://127.0.0.1:8082
|
||||||
|
python3 tests/student_tests.py --base-url http://127.0.0.1:8082
|
||||||
|
python3 tests/contract_edge_tests.py --base-url http://127.0.0.1:8082
|
||||||
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:8082
|
||||||
|
|
||||||
|
В Git файл scripts/restart.sh должен иметь режим 100755. Если рабочая копия создана на Windows, после добавления файла в индекс выполните git update-index --chmod=+x scripts/restart.sh. Для Windows проверка использует эквивалентный scripts/restart.cmd. Оба сценария останавливают API и PostgreSQL и поднимают их с тем же томом.
|
||||||
|
|
||||||
|
### Истечение сессии
|
||||||
|
|
||||||
|
Команды ниже позволяют отдельно повторить проверку истечения сессии. Выполняйте их в той же сессии PowerShell, где заданы COMPOSE_PROJECT_NAME и LAB2_HOST_PORT для основного прогона. Результат такой проверки от 23 ноября приложен отдельным логом evidence/results-docker-2026-11-23.txt.
|
||||||
|
|
||||||
|
$env:SESSION_TTL_SECONDS = '2'
|
||||||
|
try {
|
||||||
|
docker compose --env-file .env up -d --wait api
|
||||||
|
python tests/student_tests.py --expiry --base-url http://127.0.0.1:8082
|
||||||
|
} finally {
|
||||||
|
Remove-Item Env:SESSION_TTL_SECONDS
|
||||||
|
docker compose --env-file .env up -d --wait api
|
||||||
|
}
|
||||||
|
|
||||||
|
Остановка с сохранением данных выполняется командой docker compose --env-file .env down. Для намеренной очистки учебной БД предусмотрена команда docker compose --env-file .env down -v. Тест сохранности запускает только сценарий перезапуска с сохранением тома.
|
||||||
|
|
||||||
|
## Результаты проверок
|
||||||
|
|
||||||
|
| Проверка | Наблюдение | Доказательство |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Структура и конфигурация Compose | Проверка структуры и compose config --quiet прошли | [Лог Docker](evidence/results-docker.txt) |
|
||||||
|
| Сборка и запуск Compose | API и PostgreSQL стали доступны, все HTTP-тесты прошли | [Лог Docker от 30 ноября](evidence/results-docker.txt) |
|
||||||
|
| API и контракт | Публичный smoke, собственные тесты и 22 проверки граничных случаев прошли по HTTP | [Лог Docker](evidence/results-docker.txt) |
|
||||||
|
| Перезапуск API и PostgreSQL | Время запуска обоих контейнеров изменилось, имя тома осталось прежним. Публичный persistence подтвердил, что прежняя сессия читает исходное сообщение | [Лог Docker](evidence/results-docker.txt) |
|
||||||
|
| Повторный запуск миграции | После перезапуска в schema_migrations осталась ровно одна запись версии 1 | [Лог Docker](evidence/results-docker.txt) |
|
||||||
|
| Истечение сессии | При SESSION_TTL_SECONDS=2 тот же токен сначала дал 200, а после истечения получил 401 | [Отдельный прогон от 23 ноября](evidence/results-docker-2026-11-23.txt) |
|
||||||
|
| GNU Make и POSIX-скрипт перезапуска | make check, make test и make test-persistence ACTION_SCRIPT=scripts/restart.sh прошли | [Лог GNU Make](evidence/results-make-2026-12-01.txt) |
|
||||||
|
|
||||||
|
Основной прогон выполнен в Docker Desktop на Windows 30 ноября 2026 года на порту 8082. Публичный тест сохранности вызвал scripts/restart.cmd и проверил данные и действующую сессию после перезапуска обоих контейнеров. На той же версии кода 23 ноября отдельно проверено истечение сессии на порту 18082. В контейнерах использовались Python 3.12.10 и PostgreSQL 16.16.
|
||||||
|
|
||||||
|
1 декабря 2026 года дополнительно проверен отправленный коммит ca84823 через GNU Make 4.4.1 и Linux-скрипт scripts/restart.sh. Тестовый клиент работал в отдельном Linux-контейнере с Python 3.12.16, адрес API внутри сети Compose задавался через BASE_URL=http://api:8080. Образ API собран из отправленных исходников с Python 3.12.10, база работала на PostgreSQL 16.16. Проверено изменение времени запуска обоих контейнеров и сохранение имени и времени создания тома PostgreSQL. Прежняя сессия прочитала подтверждённое сообщение после рестарта, в schema_migrations осталась ровно одна запись версии 1.
|
||||||
|
|
||||||
|
## Ограничения и источники
|
||||||
|
|
||||||
|
Один экземпляр PostgreSQL хранит все данные. Потеря его тома требует восстановления из резервной копии. Страницы истории отражают доступные на момент запроса данные. Операции создания и чтения используют отдельные соединения с базой. Целевой уровень использует PostgreSQL для сессий и учебный HTTP на localhost.
|
||||||
|
|
||||||
|
Основа работы — контракт и тесты преподавателя, отправленная ЛР №1 и существующий черновик ЛР №2. Для доработки реализации, тестов и отчёта использовалась помощь ChatGPT. Поведение транзакций и порядок запуска контейнеров сверены с официальной документацией. [Psycopg](https://www.psycopg.org/psycopg3/docs/basic/transactions.html), [Docker Compose](https://docs.docker.com/compose/how-tos/startup-order/).
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
"""HTTP API of the MTUCI course messenger, lab 2."""
|
||||||
+460
@@ -0,0 +1,460 @@
|
|||||||
|
"""Lab 2: one FastAPI API, durable PostgreSQL state and opaque bearer sessions."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg.errors import UniqueViolation
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from argon2 import PasswordHasher
|
||||||
|
from argon2.exceptions import VerificationError
|
||||||
|
from fastapi import Depends, FastAPI, Request
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from fastapi.responses import JSONResponse, Response
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, StrictStr
|
||||||
|
|
||||||
|
log = logging.getLogger('messenger')
|
||||||
|
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
|
||||||
|
app = FastAPI(title='MTUCI Messenger / lab 2', docs_url=None, redoc_url=None, openapi_url=None)
|
||||||
|
KDF = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||||
|
# Even for a nonexistent user, a failed login runs a password KDF check.
|
||||||
|
DUMMY_HASH = KDF.hash('Dummy-password-not-a-real-user-123')
|
||||||
|
TTL_SECONDS = int(os.environ.get('SESSION_TTL_SECONDS', '3600'))
|
||||||
|
NAME = re.compile(r'^[a-z0-9_]{3,32}$')
|
||||||
|
TOKEN = re.compile(r'[A-Za-z0-9_-]{64}')
|
||||||
|
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||||
|
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||||
|
|
||||||
|
|
||||||
|
def utc_now() -> datetime:
|
||||||
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def timestamp(value: datetime) -> str:
|
||||||
|
return value.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
|
||||||
|
|
||||||
|
|
||||||
|
def db():
|
||||||
|
"""Open a connection whose context manager commits or rolls back."""
|
||||||
|
dsn = os.environ.get('DATABASE_URL', '')
|
||||||
|
if dsn:
|
||||||
|
return psycopg.connect(dsn, row_factory=dict_row, connect_timeout=3)
|
||||||
|
return psycopg.connect(
|
||||||
|
host=os.environ.get('POSTGRES_HOST', 'db'),
|
||||||
|
dbname=os.environ['POSTGRES_DB'],
|
||||||
|
user=os.environ['POSTGRES_USER'],
|
||||||
|
password=os.environ['POSTGRES_PASSWORD'],
|
||||||
|
row_factory=dict_row,
|
||||||
|
connect_timeout=3,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def migrate() -> None:
|
||||||
|
migration = (Path(__file__).resolve().parent.parent / 'migrations' / '001_initial.sql').read_text(encoding='utf-8')
|
||||||
|
with db() as conn:
|
||||||
|
conn.execute('SELECT pg_advisory_xact_lock(2026, 2)')
|
||||||
|
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version integer PRIMARY KEY,
|
||||||
|
applied_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)""")
|
||||||
|
installed = conn.execute('SELECT 1 FROM schema_migrations WHERE version=1').fetchone()
|
||||||
|
if not installed:
|
||||||
|
conn.execute(migration)
|
||||||
|
conn.execute('INSERT INTO schema_migrations(version) VALUES (1)')
|
||||||
|
log.info('Migration 001 checked')
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_event('startup')
|
||||||
|
def on_startup():
|
||||||
|
if TTL_SECONDS <= 0:
|
||||||
|
raise RuntimeError('SESSION_TTL_SECONDS must be a positive integer')
|
||||||
|
for attempt in range(20):
|
||||||
|
try:
|
||||||
|
migrate()
|
||||||
|
return
|
||||||
|
except psycopg.OperationalError:
|
||||||
|
if attempt == 19:
|
||||||
|
raise
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
|
||||||
|
class Error(Exception):
|
||||||
|
def __init__(self, status: int, code: str, message: str, challenge: str | None = None):
|
||||||
|
self.status, self.code, self.message, self.challenge = status, code, message, challenge
|
||||||
|
|
||||||
|
|
||||||
|
def fail(status: int, code: str, message: str, challenge: str | None = None):
|
||||||
|
raise Error(status, code, message, challenge)
|
||||||
|
|
||||||
|
|
||||||
|
def error_response(request: Request, status: int, code: str, message: str, challenge: str | None = None):
|
||||||
|
rid = getattr(request.state, 'rid', str(uuid.uuid4()))
|
||||||
|
headers = {'WWW-Authenticate': challenge} if challenge else {}
|
||||||
|
return JSONResponse(status_code=status, headers=headers,
|
||||||
|
content={'error': {'code': code, 'message': message, 'request_id': rid}})
|
||||||
|
|
||||||
|
|
||||||
|
@app.middleware('http')
|
||||||
|
async def add_request_id(request: Request, call_next):
|
||||||
|
request.state.rid = str(uuid.uuid4())
|
||||||
|
try:
|
||||||
|
response = await call_next(request)
|
||||||
|
except (psycopg.OperationalError, psycopg.InterfaceError):
|
||||||
|
log.warning('Database unavailable, request_id=%s', request.state.rid)
|
||||||
|
response = error_response(request, 503, 'unavailable', 'Хранилище недоступно')
|
||||||
|
except Exception as exc:
|
||||||
|
log.error('Unexpected %s, request_id=%s', type(exc).__name__, request.state.rid)
|
||||||
|
response = error_response(request, 500, 'internal_error', 'Внутренняя ошибка сервера')
|
||||||
|
response.headers['X-Request-Id'] = request.state.rid
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(Error)
|
||||||
|
async def on_error(request: Request, exc: Error):
|
||||||
|
return error_response(request, exc.status, exc.code, exc.message, exc.challenge)
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(RequestValidationError)
|
||||||
|
async def on_validation_error(request: Request, exc: RequestValidationError):
|
||||||
|
return error_response(request, 400, 'invalid_request', 'Неверные поля или типы запроса')
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(404)
|
||||||
|
async def on_not_found(request: Request, exc):
|
||||||
|
return error_response(request, 404, 'not_found', 'Объект не найден')
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(405)
|
||||||
|
async def on_method_not_allowed(request: Request, exc):
|
||||||
|
return error_response(request, 405, 'invalid_request', 'Метод не поддерживается')
|
||||||
|
|
||||||
|
|
||||||
|
class StrictModel(BaseModel):
|
||||||
|
model_config = ConfigDict(extra='forbid', strict=True)
|
||||||
|
|
||||||
|
|
||||||
|
class NewUser(StrictModel):
|
||||||
|
username: StrictStr = Field(min_length=3, max_length=32, pattern=r'^[a-z0-9_]{3,32}$')
|
||||||
|
display_name: StrictStr = Field(min_length=1, max_length=100)
|
||||||
|
password: StrictStr = Field(min_length=12, max_length=128)
|
||||||
|
|
||||||
|
|
||||||
|
class NewChat(StrictModel):
|
||||||
|
title: StrictStr = Field(min_length=1, max_length=100)
|
||||||
|
member_ids: list[StrictStr] = Field(min_length=1, max_length=100)
|
||||||
|
|
||||||
|
|
||||||
|
class NewMessage(StrictModel):
|
||||||
|
text: StrictStr = Field(min_length=1, max_length=4000)
|
||||||
|
|
||||||
|
|
||||||
|
async def json_body(request: Request, model):
|
||||||
|
media_type = request.headers.get('Content-Type', '').split(';', 1)[0].strip().lower()
|
||||||
|
if media_type != 'application/json':
|
||||||
|
fail(415, 'unsupported_media_type', 'Ожидается application/json')
|
||||||
|
body = bytearray()
|
||||||
|
async for chunk in request.stream():
|
||||||
|
if len(body) + len(chunk) > 1024 * 1024:
|
||||||
|
fail(413, 'payload_too_large', 'Слишком большой запрос')
|
||||||
|
body.extend(chunk)
|
||||||
|
try:
|
||||||
|
return model.model_validate(json.loads(body.decode('utf-8')))
|
||||||
|
except (ValueError, RecursionError):
|
||||||
|
fail(400, 'invalid_request', 'Неверный JSON, поля или типы запроса')
|
||||||
|
|
||||||
|
|
||||||
|
async def user_body(request: Request):
|
||||||
|
return await json_body(request, NewUser)
|
||||||
|
|
||||||
|
|
||||||
|
async def chat_body(request: Request):
|
||||||
|
return await json_body(request, NewChat)
|
||||||
|
|
||||||
|
|
||||||
|
async def message_body(request: Request):
|
||||||
|
return await json_body(request, NewMessage)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_text(value: str, *, postgres: bool = True):
|
||||||
|
if not value.strip() or (postgres and '\x00' in value):
|
||||||
|
fail(400, 'invalid_request', 'Некорректная обязательная строка')
|
||||||
|
try:
|
||||||
|
value.encode('utf-8')
|
||||||
|
except UnicodeEncodeError:
|
||||||
|
fail(400, 'invalid_request', 'Некорректный Unicode')
|
||||||
|
|
||||||
|
|
||||||
|
def valid_uuid(value: str) -> uuid.UUID:
|
||||||
|
try:
|
||||||
|
parsed = uuid.UUID(value)
|
||||||
|
if str(parsed) != value.lower():
|
||||||
|
raise ValueError()
|
||||||
|
return parsed
|
||||||
|
except (TypeError, ValueError, AttributeError):
|
||||||
|
fail(400, 'invalid_request', 'Неверный UUID')
|
||||||
|
|
||||||
|
|
||||||
|
def view_user(row: dict) -> dict:
|
||||||
|
return {key: str(row[key]) if key == 'id' else timestamp(row[key]) if key == 'created_at' else row[key]
|
||||||
|
for key in ('id', 'username', 'display_name', 'created_at')}
|
||||||
|
|
||||||
|
|
||||||
|
def view_chat(row: dict, member_ids) -> dict:
|
||||||
|
return {'id': str(row['id']), 'title': row['title'],
|
||||||
|
'member_ids': [str(i) for i in member_ids], 'created_at': timestamp(row['created_at'])}
|
||||||
|
|
||||||
|
|
||||||
|
def view_message(row: dict) -> dict:
|
||||||
|
return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'sender_id': str(row['sender_id']),
|
||||||
|
'text': row['text'], 'created_at': timestamp(row['created_at'])}
|
||||||
|
|
||||||
|
|
||||||
|
def authorization(request: Request, scheme: str) -> str:
|
||||||
|
values = request.headers.getlist('Authorization')
|
||||||
|
if len(values) != 1:
|
||||||
|
return ''
|
||||||
|
prefix, _, credential = values[0].partition(' ')
|
||||||
|
return credential.lstrip(' ') if prefix.lower() == scheme else ''
|
||||||
|
|
||||||
|
|
||||||
|
def token_digest(token: str) -> str:
|
||||||
|
return hashlib.sha256(token.encode('ascii')).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def bearer_user(request: Request) -> dict:
|
||||||
|
token = authorization(request, 'bearer')
|
||||||
|
if TOKEN.fullmatch(token) is None:
|
||||||
|
fail(401, 'unauthorized', 'Нужен действительный Bearer-токен', BEARER_CHALLENGE)
|
||||||
|
digest = token_digest(token)
|
||||||
|
with db() as conn:
|
||||||
|
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.expires_at > %s''', (digest, utc_now())).fetchone()
|
||||||
|
if not row:
|
||||||
|
fail(401, 'unauthorized', 'Сессия отсутствует или истекла', BEARER_CHALLENGE)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
Actor = Annotated[dict, Depends(bearer_user)]
|
||||||
|
|
||||||
|
|
||||||
|
def parse_limit(raw: str) -> int:
|
||||||
|
if not re.fullmatch(r'[0-9]{1,3}', raw or ''):
|
||||||
|
fail(400, 'invalid_request', 'Неверный limit')
|
||||||
|
value = int(raw)
|
||||||
|
if not (1 <= value <= 100):
|
||||||
|
fail(400, 'invalid_request', 'limit должен быть от 1 до 100')
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def encode_cursor(scope: str, row: dict) -> str:
|
||||||
|
payload = {'scope': scope, 'created_at': timestamp(row['created_at']), 'id': str(row['id'])}
|
||||||
|
return base64.urlsafe_b64encode(json.dumps(payload, separators=(',', ':')).encode()).decode().rstrip('=')
|
||||||
|
|
||||||
|
|
||||||
|
def decode_cursor(raw: str | None, scope: str):
|
||||||
|
if raw is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
if len(raw) > 1024 or re.fullmatch(r'[A-Za-z0-9_-]+', raw) is None:
|
||||||
|
raise ValueError()
|
||||||
|
data = base64.b64decode(raw + '=' * (-len(raw) % 4), altchars=b'-_', validate=True)
|
||||||
|
if base64.urlsafe_b64encode(data).decode('ascii').rstrip('=') != raw:
|
||||||
|
raise ValueError()
|
||||||
|
payload = json.loads(data.decode('utf-8'))
|
||||||
|
if not isinstance(payload, dict) or set(payload) != {'scope', 'created_at', 'id'} or payload['scope'] != scope:
|
||||||
|
raise ValueError()
|
||||||
|
at = datetime.fromisoformat(payload['created_at'].replace('Z', '+00:00'))
|
||||||
|
cursor_id = uuid.UUID(payload['id'])
|
||||||
|
if at.tzinfo is None or timestamp(at) != payload['created_at'] or str(cursor_id) != payload['id']:
|
||||||
|
raise ValueError()
|
||||||
|
return at, cursor_id
|
||||||
|
except (ValueError, TypeError, AttributeError, OverflowError, RecursionError):
|
||||||
|
fail(400, 'invalid_request', 'Неверный cursor')
|
||||||
|
|
||||||
|
|
||||||
|
def page_options(request: Request, scope: str):
|
||||||
|
query = request.query_params
|
||||||
|
if set(query) - {'limit', 'cursor'} or any(len(query.getlist(name)) > 1 for name in ('limit', 'cursor')):
|
||||||
|
fail(400, 'invalid_request', 'Некорректные параметры страницы')
|
||||||
|
return parse_limit(query.get('limit', '50')), decode_cursor(query.get('cursor'), scope)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/health/live')
|
||||||
|
def live():
|
||||||
|
return {'status': 'ok'}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/health/ready')
|
||||||
|
def ready():
|
||||||
|
try:
|
||||||
|
with db() as conn:
|
||||||
|
migrated = conn.execute('SELECT 1 FROM schema_migrations WHERE version = 1').fetchone()
|
||||||
|
except psycopg.Error:
|
||||||
|
fail(503, 'unavailable', 'PostgreSQL недоступен')
|
||||||
|
if not migrated:
|
||||||
|
fail(503, 'unavailable', 'Схема PostgreSQL не готова')
|
||||||
|
return {'status': 'ok'}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post('/api/v1/users', status_code=201)
|
||||||
|
def create_user(data: Annotated[NewUser, Depends(user_body)]):
|
||||||
|
validate_text(data.display_name)
|
||||||
|
validate_text(data.password, postgres=False)
|
||||||
|
record = (uuid.uuid4(), data.username, data.display_name, KDF.hash(data.password), utc_now())
|
||||||
|
try:
|
||||||
|
with db() as conn:
|
||||||
|
row = conn.execute('''INSERT INTO users(id,username,display_name,password_hash,created_at)
|
||||||
|
VALUES (%s,%s,%s,%s,%s) RETURNING *''', record).fetchone()
|
||||||
|
except UniqueViolation:
|
||||||
|
fail(409, 'conflict', 'Имя пользователя занято')
|
||||||
|
return view_user(row)
|
||||||
|
|
||||||
|
|
||||||
|
async def basic_credentials(request: Request):
|
||||||
|
try:
|
||||||
|
decoded = base64.b64decode(authorization(request, 'basic'), validate=True).decode('utf-8')
|
||||||
|
username, password = decoded.split(':', 1)
|
||||||
|
if not NAME.fullmatch(username) or not (12 <= len(password) <= 128):
|
||||||
|
raise ValueError()
|
||||||
|
except ValueError:
|
||||||
|
fail(401, 'unauthorized', 'Неверные учётные данные', BASIC_CHALLENGE)
|
||||||
|
async for chunk in request.stream():
|
||||||
|
if chunk:
|
||||||
|
fail(400, 'invalid_request', 'Вход принимает только заголовок Authorization')
|
||||||
|
return username, password
|
||||||
|
|
||||||
|
|
||||||
|
@app.post('/api/v1/auth/sessions', status_code=201)
|
||||||
|
def login(credentials: Annotated[tuple[str, str], Depends(basic_credentials)]):
|
||||||
|
username, password = credentials
|
||||||
|
with db() as conn:
|
||||||
|
row = conn.execute('SELECT * FROM users WHERE username=%s', (username,)).fetchone()
|
||||||
|
try:
|
||||||
|
verified = KDF.verify(row['password_hash'] if row else DUMMY_HASH, password)
|
||||||
|
except VerificationError:
|
||||||
|
verified = False
|
||||||
|
if not row or not verified:
|
||||||
|
fail(401, 'unauthorized', 'Неверные учётные данные', BASIC_CHALLENGE)
|
||||||
|
token = secrets.token_urlsafe(48)
|
||||||
|
issued = utc_now()
|
||||||
|
expires = issued + timedelta(seconds=TTL_SECONDS)
|
||||||
|
with db() as conn:
|
||||||
|
conn.execute('''INSERT INTO sessions(token_hash,user_id,expires_at,created_at)
|
||||||
|
VALUES (%s,%s,%s,%s)''', (token_digest(token), row['id'], expires, issued))
|
||||||
|
return {'token': token, 'token_type': 'Bearer', 'expires_at': timestamp(expires), 'user': view_user(row)}
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete('/api/v1/auth/sessions/current', status_code=204)
|
||||||
|
def logout(request: Request, actor: Actor):
|
||||||
|
token = authorization(request, 'bearer')
|
||||||
|
with db() as conn:
|
||||||
|
removed = conn.execute('DELETE FROM sessions WHERE token_hash=%s', (token_digest(token),)).rowcount
|
||||||
|
if not removed:
|
||||||
|
fail(401, 'unauthorized', 'Сессия отсутствует или истекла', BEARER_CHALLENGE)
|
||||||
|
return Response(status_code=204)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/api/v1/users/me')
|
||||||
|
def me(actor: Actor):
|
||||||
|
return view_user(actor)
|
||||||
|
|
||||||
|
|
||||||
|
def get_members(conn, chat_id):
|
||||||
|
return [r['user_id'] for r in conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id', (chat_id,)).fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
def accessible_chat(conn, chat_id: str, user_id: uuid.UUID):
|
||||||
|
cid = valid_uuid(chat_id)
|
||||||
|
row = 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_id)).fetchone()
|
||||||
|
if not row:
|
||||||
|
fail(404, 'not_found', 'Чат не найден')
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
@app.post('/api/v1/chats', status_code=201)
|
||||||
|
def create_chat(actor: Actor, data: Annotated[NewChat, Depends(chat_body)]):
|
||||||
|
validate_text(data.title)
|
||||||
|
ids = [valid_uuid(item) for item in data.member_ids]
|
||||||
|
if len(ids) != len(set(ids)) or actor['id'] not in ids:
|
||||||
|
fail(400, 'invalid_request', 'Некорректный список участников')
|
||||||
|
cid = uuid.uuid4()
|
||||||
|
created_at = utc_now()
|
||||||
|
with db() as conn:
|
||||||
|
n = conn.execute('SELECT COUNT(*) AS total FROM users WHERE id=ANY(%s::uuid[])', (ids,)).fetchone()['total']
|
||||||
|
if n != len(ids):
|
||||||
|
fail(400, 'invalid_request', 'Неизвестный участник')
|
||||||
|
row = conn.execute('INSERT INTO chats(id,title,created_at) VALUES (%s,%s,%s) RETURNING *',
|
||||||
|
(cid, data.title, created_at)).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 view_chat(row, sorted(ids))
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/api/v1/chats')
|
||||||
|
def list_chats(request: Request, actor: Actor):
|
||||||
|
scope = 'chats:' + str(actor['id'])
|
||||||
|
page_size, since = page_options(request, scope)
|
||||||
|
with db() as conn:
|
||||||
|
rows = conn.execute('''SELECT c.id,c.title,c.created_at FROM chats c
|
||||||
|
JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s
|
||||||
|
AND (%s::timestamptz IS NULL OR (c.created_at,c.id)>(%s::timestamptz,%s::uuid))
|
||||||
|
ORDER BY c.created_at,c.id LIMIT %s''',
|
||||||
|
(actor['id'], since[0] if since else None, since[0] if since else None,
|
||||||
|
since[1] if since else None, page_size + 1)).fetchall()
|
||||||
|
page = rows[:page_size]
|
||||||
|
items = [view_chat(r, get_members(conn, r['id'])) for r in page]
|
||||||
|
return {'items': items, 'next_cursor': encode_cursor(scope, page[-1]) if len(rows) > page_size else None}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/api/v1/chats/{chat_id}')
|
||||||
|
def get_chat(chat_id: str, actor: Actor):
|
||||||
|
with db() as conn:
|
||||||
|
row = accessible_chat(conn, chat_id, actor['id'])
|
||||||
|
members = get_members(conn, row['id'])
|
||||||
|
return view_chat(row, members)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post('/api/v1/chats/{chat_id}/messages', status_code=201)
|
||||||
|
def create_message(chat_id: str, actor: Actor, data: Annotated[NewMessage, Depends(message_body)]):
|
||||||
|
validate_text(data.text)
|
||||||
|
with db() as conn:
|
||||||
|
chat = accessible_chat(conn, chat_id, actor['id'])
|
||||||
|
row = conn.execute('''INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||||
|
VALUES (%s,%s,%s,%s,%s) RETURNING *''',
|
||||||
|
(uuid.uuid4(), chat['id'], actor['id'], data.text, utc_now())).fetchone()
|
||||||
|
return view_message(row)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/api/v1/chats/{chat_id}/messages')
|
||||||
|
def list_messages(chat_id: str, request: Request, actor: Actor):
|
||||||
|
with db() as conn:
|
||||||
|
chat = accessible_chat(conn, chat_id, actor['id'])
|
||||||
|
scope = 'messages:' + str(chat['id'])
|
||||||
|
page_size, since = page_options(request, scope)
|
||||||
|
rows = conn.execute('''SELECT * FROM messages WHERE chat_id=%s
|
||||||
|
AND (%s::timestamptz IS NULL OR (created_at,id)>(%s::timestamptz,%s::uuid))
|
||||||
|
ORDER BY created_at,id LIMIT %s''',
|
||||||
|
(chat['id'], since[0] if since else None, since[0] if since else None,
|
||||||
|
since[1] if since else None, page_size + 1)).fetchall()
|
||||||
|
return {'items': [view_message(row) for row in rows[:page_size]],
|
||||||
|
'next_cursor': encode_cursor(scope, rows[page_size - 1]) if len(rows) > page_size else None}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import uvicorn
|
||||||
|
uvicorn.run(app, host=os.environ.get('APP_HOST', '0.0.0.0'), port=int(os.environ.get('APP_PORT', '8080')),
|
||||||
|
access_log=False, workers=1)
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
name: mtusi-lab2
|
||||||
|
services:
|
||||||
|
db:
|
||||||
|
image: postgres:16.16-bookworm
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:?set POSTGRES_USER in .env}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:?set POSTGRES_DB in .env}
|
||||||
|
volumes:
|
||||||
|
- pgdata:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\""]
|
||||||
|
interval: 2s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
api:
|
||||||
|
build: .
|
||||||
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
environment:
|
||||||
|
POSTGRES_HOST: db
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:?set POSTGRES_USER in .env}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:?set POSTGRES_DB in .env}
|
||||||
|
APP_HOST: 0.0.0.0
|
||||||
|
APP_PORT: 8080
|
||||||
|
APP_ENV: lab
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${LAB2_HOST_PORT:-8080}:8080"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=3).close()"]
|
||||||
|
interval: 3s
|
||||||
|
timeout: 4s
|
||||||
|
retries: 15
|
||||||
|
start_period: 5s
|
||||||
|
volumes:
|
||||||
|
pgdata:
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
Docker verification 2026-11-23T23:56:41.1815671+03:00
|
||||||
|
PASS: Compose build and startup (http://127.0.0.1:18082)
|
||||||
|
python -X utf8 scripts/check_contract.py
|
||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
|
python tests/smoke.py --base-url http://127.0.0.1:18082
|
||||||
|
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
python tests/student_tests.py --base-url http://127.0.0.1:18082
|
||||||
|
PASS: validation, Unicode Basic login, access, pagination and logout
|
||||||
|
python tests/contract_edge_tests.py --base-url http://127.0.0.1:18082
|
||||||
|
PASS: 22 Lab 2 contract edge-case HTTP checks
|
||||||
|
Before restart: api=2026-11-23T20:56:35.336160953Z db=2026-11-23T20:56:32.651654239Z volume=mtusi-lab2-review-1123_pgdata
|
||||||
|
python tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://127.0.0.1:18082
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
After restart: api=2026-11-23T20:56:48.209619191Z db=2026-11-23T20:56:45.52776417Z volume=mtusi-lab2-review-1123_pgdata
|
||||||
|
PASS: both Docker containers restarted and the database volume was retained
|
||||||
|
PASS: PostgreSQL has exactly one migration record with version 1 after restart
|
||||||
|
SESSION_TTL_SECONDS=2; python tests/student_tests.py --expiry --base-url http://127.0.0.1:18082
|
||||||
|
PASS: Bearer session expires without logout
|
||||||
|
Python 3.12.10
|
||||||
|
postgres (PostgreSQL) 16.16 (Debian 16.16-1.pgdg12+1)
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
Docker verification 2026-11-30T09:38:26.7768121+03:00
|
||||||
|
PASS: Compose build and startup (http://127.0.0.1:8082)
|
||||||
|
python -X utf8 scripts/check_contract.py
|
||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
|
python tests/smoke.py --base-url http://127.0.0.1:8082
|
||||||
|
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
python tests/student_tests.py --base-url http://127.0.0.1:8082
|
||||||
|
PASS: validation, Unicode Basic login, access, pagination and logout
|
||||||
|
python tests/contract_edge_tests.py --base-url http://127.0.0.1:8082
|
||||||
|
PASS: 22 Lab 2 contract edge-case HTTP checks
|
||||||
|
Before restart: api=2026-11-30T06:38:19.803038106Z db=2026-11-30T06:38:16.990609434Z volume=mtusi-lab2-selfcheck-20261130093752_pgdata
|
||||||
|
python tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://127.0.0.1:8082
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
After restart: api=2026-11-30T06:38:38.606049433Z db=2026-11-30T06:38:35.806522427Z volume=mtusi-lab2-selfcheck-20261130093752_pgdata
|
||||||
|
PASS: both Docker containers restarted and the database volume was retained
|
||||||
|
PASS: PostgreSQL has exactly one migration record with version 1 after restart
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
POSIX Make verification 2026-12-01T11:12:12Z
|
||||||
|
Submitted commit ca84823281539a3e1343f88ccf967defe632c40d
|
||||||
|
Python 3.12.16
|
||||||
|
GNU Make 4.4.1
|
||||||
|
Docker Compose version v2.35.0
|
||||||
|
BASE_URL=http://api:8080
|
||||||
|
Command: make check
|
||||||
|
python3 scripts/check_contract.py
|
||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
|
Command: make test
|
||||||
|
python3 tests/smoke.py --base-url "http://api:8080"
|
||||||
|
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
Before restart: api=2026-12-01T11:11:29.358865668Z db=2026-12-01T11:11:26.64639198Z volume=mtusi-lab2-make-1201_pgdata volume_created=2026-12-01T11:11:26Z
|
||||||
|
Command: make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://api:8080"
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
After restart: api=2026-12-01T11:12:20.066788274Z db=2026-12-01T11:12:17.310082973Z volume=mtusi-lab2-make-1201_pgdata volume_created=2026-12-01T11:11:26Z
|
||||||
|
PASS: POSIX restart.sh restarted API and PostgreSQL and retained the original database volume
|
||||||
|
PASS: schema_migrations still contains exactly one migration, version 1
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
-- Lab 2, migration 001. Transactional, idempotent DDL for an empty database.
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
username varchar(32) NOT NULL UNIQUE,
|
||||||
|
display_name varchar(100) NOT NULL,
|
||||||
|
password_hash text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL,
|
||||||
|
CONSTRAINT users_name_format CHECK (username ~ '^[a-z0-9_]{3,32}$')
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS chats (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
title varchar(100) NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_members (
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||||
|
PRIMARY KEY (chat_id, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_members_user ON chat_members(user_id, chat_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_chats_order ON chats(created_at, id);
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||||
|
text varchar(4000) NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL,
|
||||||
|
CONSTRAINT message_not_blank CHECK (length(btrim(text)) > 0)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_page ON messages(chat_id, created_at, id);
|
||||||
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
token_hash char(64) PRIMARY KEY,
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
expires_at timestamptz NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sessions_expiry ON sessions(expires_at);
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
fastapi==0.115.12
|
||||||
|
uvicorn==0.34.2
|
||||||
|
psycopg[binary]==3.2.6
|
||||||
|
argon2-cffi==25.1.0
|
||||||
|
pydantic==2.14.3
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
@echo off
|
||||||
|
REM Windows PowerShell persistence test hook; no volume deletion.
|
||||||
|
cd /d "%~dp0.."
|
||||||
|
docker compose --env-file .env stop api db || exit /b 1
|
||||||
|
docker compose --env-file .env up -d --wait --wait-timeout 45 db api || exit /b 1
|
||||||
Executable
+6
@@ -0,0 +1,6 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Explicit persistence test hook. Retains the named database volume.
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
docker compose --env-file .env stop api db
|
||||||
|
docker compose --env-file .env up -d --wait --wait-timeout 45 db api
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
param(
|
||||||
|
[ValidateRange(1, 65535)]
|
||||||
|
[int]$Port = 8080
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$previousHostPort = [Environment]::GetEnvironmentVariable('LAB2_HOST_PORT', 'Process')
|
||||||
|
|
||||||
|
function Assert-NativeSuccess([string]$Step) {
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "$Step failed (exit code $LASTEXITCODE)" }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-Evidence([string]$Line) {
|
||||||
|
Add-Content -LiteralPath $evidence -Value $Line -Encoding UTF8
|
||||||
|
Write-Host $Line
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-PythonCheck([string[]]$Arguments) {
|
||||||
|
Write-Evidence ("python " + ($Arguments -join ' '))
|
||||||
|
& python @Arguments | ForEach-Object { Write-Evidence $_ }
|
||||||
|
Assert-NativeSuccess 'Python check'
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-ContainerState {
|
||||||
|
$api = docker compose --env-file .env ps --quiet api
|
||||||
|
Assert-NativeSuccess 'API container lookup'
|
||||||
|
$db = docker compose --env-file .env ps --quiet db
|
||||||
|
Assert-NativeSuccess 'PostgreSQL container lookup'
|
||||||
|
if (!$api -or !$db) { throw 'Expected running api and db containers' }
|
||||||
|
$apiStarted = docker inspect --format '{{.State.StartedAt}}' $api
|
||||||
|
Assert-NativeSuccess 'API start time lookup'
|
||||||
|
$dbStarted = docker inspect --format '{{.State.StartedAt}}' $db
|
||||||
|
Assert-NativeSuccess 'PostgreSQL start time lookup'
|
||||||
|
$volume = docker inspect --format '{{range .Mounts}}{{.Name}}{{end}}' $db
|
||||||
|
Assert-NativeSuccess 'PostgreSQL volume lookup'
|
||||||
|
if (!$volume) { throw 'Expected a named PostgreSQL volume' }
|
||||||
|
[pscustomobject]@{ ApiStarted = $apiStarted; DbStarted = $dbStarted; Volume = $volume }
|
||||||
|
}
|
||||||
|
|
||||||
|
Push-Location -LiteralPath (Join-Path $PSScriptRoot '..')
|
||||||
|
try {
|
||||||
|
if ($PSBoundParameters.ContainsKey('Port')) {
|
||||||
|
$env:LAB2_HOST_PORT = [string]$Port
|
||||||
|
}
|
||||||
|
if (!(Test-Path -LiteralPath '.env')) {
|
||||||
|
$password = python -B -c 'import secrets; print(secrets.token_hex(24))'
|
||||||
|
Assert-NativeSuccess 'Test password generation'
|
||||||
|
$settings = Get-Content -LiteralPath '.env.example'
|
||||||
|
$settings -replace '^POSTGRES_PASSWORD=.*', "POSTGRES_PASSWORD=$password" -replace '^LAB2_HOST_PORT=.*', "LAB2_HOST_PORT=$Port" |
|
||||||
|
Set-Content -LiteralPath '.env' -Encoding Ascii
|
||||||
|
}
|
||||||
|
docker compose --env-file .env config --quiet
|
||||||
|
Assert-NativeSuccess 'Compose configuration'
|
||||||
|
docker compose --env-file .env up -d --build --wait --wait-timeout 60
|
||||||
|
Assert-NativeSuccess 'Compose startup'
|
||||||
|
$address = docker compose --env-file .env port api 8080
|
||||||
|
Assert-NativeSuccess 'API port lookup'
|
||||||
|
if ($address -notmatch '^127\.0\.0\.1:\d+$') { throw "Unexpected API address: $address" }
|
||||||
|
$base = "http://$address"
|
||||||
|
$evidence = 'evidence/results-docker.txt'
|
||||||
|
Set-Content -LiteralPath $evidence -Value ("Docker verification " + (Get-Date -Format o)) -Encoding UTF8
|
||||||
|
Write-Evidence "PASS: Compose build and startup ($base)"
|
||||||
|
Invoke-PythonCheck @('-X', 'utf8', 'scripts/check_contract.py')
|
||||||
|
Invoke-PythonCheck @('tests/smoke.py', '--base-url', $base)
|
||||||
|
Invoke-PythonCheck @('tests/student_tests.py', '--base-url', $base)
|
||||||
|
Invoke-PythonCheck @('tests/contract_edge_tests.py', '--base-url', $base)
|
||||||
|
$before = Get-ContainerState
|
||||||
|
Write-Evidence "Before restart: api=$($before.ApiStarted) db=$($before.DbStarted) volume=$($before.Volume)"
|
||||||
|
Invoke-PythonCheck @('tests/resilience.py', '--mode', 'persistence', '--action-script', 'scripts/restart.cmd', '--base-url', $base)
|
||||||
|
$after = Get-ContainerState
|
||||||
|
Write-Evidence "After restart: api=$($after.ApiStarted) db=$($after.DbStarted) volume=$($after.Volume)"
|
||||||
|
if ($before.ApiStarted -eq $after.ApiStarted -or $before.DbStarted -eq $after.DbStarted -or $before.Volume -ne $after.Volume) {
|
||||||
|
throw 'Restart check expected new start times for both containers and the same PostgreSQL volume'
|
||||||
|
}
|
||||||
|
Write-Evidence 'PASS: both Docker containers restarted and the database volume was retained'
|
||||||
|
|
||||||
|
$dbUser = docker compose --env-file .env exec -T db printenv POSTGRES_USER
|
||||||
|
Assert-NativeSuccess 'PostgreSQL role lookup'
|
||||||
|
$dbName = docker compose --env-file .env exec -T db printenv POSTGRES_DB
|
||||||
|
Assert-NativeSuccess 'PostgreSQL database lookup'
|
||||||
|
$migration = @(docker compose --env-file .env exec -T db psql -X -At -v ON_ERROR_STOP=1 -U $dbUser -d $dbName -c 'SELECT version FROM schema_migrations ORDER BY version')
|
||||||
|
Assert-NativeSuccess 'Migration check'
|
||||||
|
if ($migration.Count -ne 1 -or $migration[0] -ne '1') {
|
||||||
|
throw 'Expected one applied migration with version 1'
|
||||||
|
}
|
||||||
|
Write-Evidence 'PASS: PostgreSQL has exactly one migration record with version 1 after restart'
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
[Environment]::SetEnvironmentVariable('LAB2_HOST_PORT', $previousHostPort, 'Process')
|
||||||
|
Pop-Location
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
"""Focused Lab 2 contract checks (stdlib only). Needs running API + PostgreSQL.
|
||||||
|
|
||||||
|
Run: python tests/contract_edge_tests.py --base-url http://localhost:8080
|
||||||
|
Prints only status summary; credentials/tokens remain in process memory.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
|
||||||
|
class Client:
|
||||||
|
def __init__(self, base):
|
||||||
|
self.base = base.rstrip('/')
|
||||||
|
self.count = 0
|
||||||
|
|
||||||
|
def call(self, method, path, expected, payload=None, auth=None, raw=None, content_type=None):
|
||||||
|
headers = {'Accept': 'application/json'}
|
||||||
|
if auth:
|
||||||
|
headers['Authorization'] = auth
|
||||||
|
if payload is not None:
|
||||||
|
raw = json.dumps(payload, ensure_ascii=True).encode('utf-8')
|
||||||
|
content_type = 'application/json'
|
||||||
|
if content_type:
|
||||||
|
headers['Content-Type'] = content_type
|
||||||
|
req = urllib.request.Request(self.base + path, data=raw, headers=headers, method=method)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=15) as response:
|
||||||
|
code = response.status
|
||||||
|
body = response.read()
|
||||||
|
reply_headers = response.headers
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
code = error.code
|
||||||
|
body = error.read()
|
||||||
|
reply_headers = error.headers
|
||||||
|
if code != expected:
|
||||||
|
raise AssertionError(f'{method} {path}: expected {expected}, received {code}')
|
||||||
|
if not reply_headers.get('X-Request-Id'):
|
||||||
|
raise AssertionError(f'{method} {path}: missing X-Request-Id')
|
||||||
|
self.count += 1
|
||||||
|
return json.loads(body) if body else None
|
||||||
|
|
||||||
|
|
||||||
|
def run(base):
|
||||||
|
c = Client(base)
|
||||||
|
prefix = uuid.uuid4().hex[:14]
|
||||||
|
name = 'ct_' + prefix
|
||||||
|
password = 'ContractTest-' + uuid.uuid4().hex[:16]
|
||||||
|
user_path = '/api/v1/users'
|
||||||
|
actor_path = '/api/v1/auth/sessions'
|
||||||
|
registration = {'username': name, 'display_name': 'Тест Unicode', 'password': password}
|
||||||
|
|
||||||
|
# Public registration must reject unknown fields and malformed Unicode.
|
||||||
|
c.call('POST', user_path, 400, payload={**registration, 'unknown': 'field'})
|
||||||
|
c.call('POST', user_path, 400, payload={**registration, 'display_name': '\ud800'})
|
||||||
|
c.call('POST', user_path, 415, raw=b'{}', content_type='text/plain')
|
||||||
|
user = c.call('POST', user_path, 201, payload=registration)
|
||||||
|
if user['username'] != name:
|
||||||
|
raise AssertionError('registration username mismatch')
|
||||||
|
|
||||||
|
basic = 'Basic ' + base64.b64encode((name + ':' + password).encode('utf-8')).decode('ascii')
|
||||||
|
# Login is Basic-only, without a JSON request body.
|
||||||
|
c.call('POST', actor_path, 400, auth=basic, payload={'unknown': 'field'})
|
||||||
|
session = c.call('POST', actor_path, 201, auth=basic)
|
||||||
|
bearer = 'Bearer ' + session['token']
|
||||||
|
|
||||||
|
# Protected POST endpoints must authenticate before parsing malformed JSON.
|
||||||
|
c.call('POST', '/api/v1/chats', 401, raw=b'{invalid', content_type='application/json')
|
||||||
|
c.call('POST', '/api/v1/chats', 400, auth=bearer, raw=b'{invalid', content_type='application/json')
|
||||||
|
c.call('POST', '/api/v1/chats', 415, auth=bearer, raw=b'{}', content_type='text/plain')
|
||||||
|
|
||||||
|
c.call('GET', '/api/v1/chats/' + uuid.uuid4().hex, 400, auth=bearer)
|
||||||
|
c.call('POST', '/api/v1/chats', 400, auth=bearer,
|
||||||
|
payload={'title': 'duplicate', 'member_ids': [user['id'], user['id']]})
|
||||||
|
c.call('POST', '/api/v1/chats', 400, auth=bearer,
|
||||||
|
payload={'title': 'missing author', 'member_ids': [str(uuid.uuid4())]})
|
||||||
|
chat1 = c.call('POST', '/api/v1/chats', 201, auth=bearer,
|
||||||
|
payload={'title': 'Page A', 'member_ids': [user['id']]})
|
||||||
|
chat2 = c.call('POST', '/api/v1/chats', 201, auth=bearer,
|
||||||
|
payload={'title': 'Page B', 'member_ids': [user['id']]})
|
||||||
|
msg_path1 = '/api/v1/chats/' + chat1['id'] + '/messages'
|
||||||
|
msg_path2 = '/api/v1/chats/' + chat2['id'] + '/messages'
|
||||||
|
c.call('POST', msg_path1, 401, raw=b'{invalid', content_type='application/json')
|
||||||
|
c.call('POST', msg_path1, 400, auth=bearer, raw=b'{invalid', content_type='application/json')
|
||||||
|
for i in range(2):
|
||||||
|
c.call('POST', msg_path1, 201, auth=bearer, payload={'text': f'Page test {i}'})
|
||||||
|
page = c.call('GET', msg_path1 + '?limit=1', 200, auth=bearer)
|
||||||
|
cursor = page.get('next_cursor')
|
||||||
|
if not cursor or len(page['items']) != 1:
|
||||||
|
raise AssertionError('expected next_cursor for two messages')
|
||||||
|
c.call('GET', msg_path2 + '?limit=1&cursor=' + urllib.parse.quote(cursor, safe=''), 400, auth=bearer)
|
||||||
|
c.call('GET', msg_path1 + '?limit=1&limit=2', 400, auth=bearer)
|
||||||
|
c.call('GET', msg_path1 + '?limit=1&cursor=@invalid@', 400, auth=bearer)
|
||||||
|
print(f'PASS: {c.count} Lab 2 contract edge-case HTTP checks')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||||
|
args = parser.parse_args()
|
||||||
|
run(args.base_url)
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
"""Simple grade-3 negative scenarios; run with the API+Postgres already started."""
|
||||||
|
import base64
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from client import Client, arguments, check, run
|
||||||
|
|
||||||
|
|
||||||
|
def configure(parser):
|
||||||
|
parser.add_argument('--expiry', action='store_true', help='Run only with SESSION_TTL_SECONDS=2')
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = arguments('Lab 2 student tests', configure)
|
||||||
|
c = Client(args.base_url, args.ca_file)
|
||||||
|
if args.expiry:
|
||||||
|
user = c.user('expiry')
|
||||||
|
c.call('GET', '/api/v1/users/me', actor=user, schema='User')
|
||||||
|
deadline = time.monotonic() + 12
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
response = c.call('GET', '/api/v1/users/me', (200, 401), actor=user, schema='User')
|
||||||
|
if response['status'] == 401:
|
||||||
|
print('PASS: Bearer session expires without logout')
|
||||||
|
return
|
||||||
|
time.sleep(0.25)
|
||||||
|
check(False, 'session did not expire; start API with SESSION_TTL_SECONDS=2')
|
||||||
|
|
||||||
|
alice, _, outsider, chat = c.bootstrap()
|
||||||
|
path = '/api/v1/chats/' + chat['id']
|
||||||
|
login_path = '/api/v1/auth/sessions'
|
||||||
|
json_header = {'Content-Type': 'application/json'}
|
||||||
|
c.call('POST', '/api/v1/users', 409, body=alice['registration'])
|
||||||
|
c.call('POST', '/api/v1/users', 400, raw=b'{invalid', headers=json_header)
|
||||||
|
c.call('POST', '/api/v1/chats', 401, raw=b'{invalid', headers=json_header)
|
||||||
|
c.call('POST', path + '/messages', 401, raw=b'{invalid', headers=json_header)
|
||||||
|
c.call('GET', path, 404, actor=outsider)
|
||||||
|
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
|
||||||
|
c.call('GET', path + '/messages?limit=0', 400, actor=alice)
|
||||||
|
c.call('GET', '/api/v1/chats/' + chat['id'].replace('-', ''), 400, actor=alice)
|
||||||
|
|
||||||
|
username = 'unicode_' + uuid.uuid4().hex[:12]
|
||||||
|
password = 'Пароль:abc-123456'
|
||||||
|
bad = f'{{"username":"{username}","display_name":"\\ud800","password":"{password}"}}'.encode('utf-8')
|
||||||
|
c.call('POST', '/api/v1/users', 400, raw=bad, headers=json_header)
|
||||||
|
registered = c.call('POST', '/api/v1/users', 201, schema='User',
|
||||||
|
body={'username': username, 'display_name': 'Проверка 👋', 'password': password})['json']
|
||||||
|
credentials = base64.b64encode(f'{username}:{password}'.encode('utf-8')).decode('ascii')
|
||||||
|
auth = {'Authorization': 'Basic ' + credentials}
|
||||||
|
c.call('POST', login_path, 400, body={}, headers=auth)
|
||||||
|
session = c.call('POST', login_path, 201, headers=auth, schema='Session')['json']
|
||||||
|
check(session['user'] == registered, 'Unicode Basic login returned the wrong user')
|
||||||
|
|
||||||
|
c.message(alice, chat, 'Первая запись')
|
||||||
|
c.message(alice, chat, 'Вторая запись')
|
||||||
|
first = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']
|
||||||
|
check(bool(first['next_cursor']), 'missing second page')
|
||||||
|
c.call('GET', path + '/messages?cursor=' + quote(first['next_cursor'] + '!', safe=''), 400, actor=alice)
|
||||||
|
second = c.call('GET', path + '/messages?limit=1&cursor=' + quote(first['next_cursor'], safe=''),
|
||||||
|
actor=alice, schema='MessagePage')['json']
|
||||||
|
check(len(second['items']) == 1 and second['next_cursor'] is None, 'incorrect last page')
|
||||||
|
check(first['items'][0]['id'] != second['items'][0]['id'], 'pagination repeated a message')
|
||||||
|
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||||
|
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||||
|
print('PASS: validation, Unicode Basic login, access, pagination and logout')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run(main)
|
||||||
Reference in New Issue
Block a user