forked from mtusi2026/mtusi2026lab2
feat: add evidence, report.md
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
# Стенд: сервисы, образы, volumes
|
||||
# date: 2026-10-21T08:43:00Z
|
||||
# commit: 1d5c1e0 (dirty)
|
||||
|
||||
$ docker compose ps -a --format table {{.Service}}\t{{.Image}}\t{{.Status}}
|
||||
SERVICE IMAGE STATUS
|
||||
api mtusi-messenger-lab2-api:dev Up 3 minutes (healthy)
|
||||
migrate mtusi-messenger-lab2-migrate:dev Exited (0) 3 minutes ago
|
||||
postgres postgres:17.2-alpine Up 3 minutes (healthy)
|
||||
redis redis:7.4.1-alpine Up 3 minutes (healthy)
|
||||
secrets-init alpine:3.20.3 Exited (0) 3 minutes ago
|
||||
tools mtusi-messenger-lab2-tools:dev Up Less than a second
|
||||
|
||||
$ docker compose images
|
||||
CONTAINER REPOSITORY TAG IMAGE ID SIZE
|
||||
messenger-lab2-api-1 mtusi-messenger-lab2-api dev c31d4a70b51e 120MB
|
||||
messenger-lab2-migrate-1 mtusi-messenger-lab2-migrate dev 667d23f25911 222MB
|
||||
messenger-lab2-postgres-1 postgres 17.2-alpine 7e5df973a748 111MB
|
||||
messenger-lab2-redis-1 redis 7.4.1-alpine c1e88455c852 19.5MB
|
||||
messenger-lab2-secrets-init-1 alpine 3.20.3 1e42bbe25081 3.63MB
|
||||
messenger-lab2-tools-run-dfc45c17a350 mtusi-messenger-lab2-tools dev 6cfc41d8a0b5 83MB
|
||||
|
||||
$ docker volume ls --filter name=messenger-lab2
|
||||
DRIVER VOLUME NAME
|
||||
local messenger-lab2_pgdata
|
||||
local messenger-lab2_secrets
|
||||
|
||||
$ docker compose exec -T postgres postgres --version
|
||||
postgres (PostgreSQL) 17.2
|
||||
|
||||
$ docker compose exec -T redis redis-server --version
|
||||
Redis server v=7.4.1 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=a93ce81042b3a6d7
|
||||
|
||||
$ docker compose exec -T redis sh -c redis-cli --no-auth-warning -a "$(cat /run/secrets/redis_password)" config get appendonly
|
||||
appendonly
|
||||
no
|
||||
|
||||
## Повторный запуск миграций и сверка схемы Prisma с БД
|
||||
$ docker compose run --rm migrate
|
||||
Container messenger-lab2-secrets-init-1 Created
|
||||
Container messenger-lab2-postgres-1 Running
|
||||
Container messenger-lab2-secrets-init-1 Starting
|
||||
Container messenger-lab2-secrets-init-1 Started
|
||||
Container messenger-lab2-secrets-init-1 Waiting
|
||||
Container messenger-lab2-secrets-init-1 Exited
|
||||
Prisma schema loaded from prisma/schema.prisma
|
||||
Datasource "db": PostgreSQL database "messenger", schema "public" at "postgres:5432"
|
||||
|
||||
2 migrations found in prisma/migrations
|
||||
|
||||
|
||||
No pending migrations to apply.
|
||||
|
||||
$ docker compose run --rm --no-deps migrate sh -c export DATABASE_URL="$(cat "$DATABASE_URL_FILE")"; npx prisma migrate diff --from-url "$DATABASE_URL" --to-schema-datamodel prisma/schema.prisma --exit-code
|
||||
No difference detected.
|
||||
|
||||
|
||||
$ docker compose exec -T postgres psql -U messenger -d messenger -c SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY started_at
|
||||
migration_name | finished_at
|
||||
------------------------------+-------------------------------
|
||||
20261021000000_init | 2026-10-21 07:22:51.225235+00
|
||||
20261021010000_auth_sessions | 2026-10-21 07:22:51.249301+00
|
||||
(2 rows)
|
||||
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# EXPLAIN (ANALYZE, BUFFERS) истории: 10 000 сообщений в чате, 50 000 всего (транзакция с ROLLBACK)
|
||||
# date: 2026-10-21T08:44:31Z
|
||||
# commit: 1d5c1e0 (dirty)
|
||||
|
||||
Pager usage is off.
|
||||
BEGIN
|
||||
INSERT 0 1
|
||||
INSERT 0 1
|
||||
INSERT 0 20
|
||||
INSERT 0 21
|
||||
INSERT 0 50000
|
||||
ANALYZE
|
||||
target_chat_messages | total_messages
|
||||
----------------------+----------------
|
||||
10000 | 50030
|
||||
(1 row)
|
||||
|
||||
=== 1. Keyset, first page (index messages_chat_id_created_at_id_idx)
|
||||
QUERY PLAN
|
||||
------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=0.41..18.25 rows=51 width=78) (actual time=0.023..0.042 rows=51 loops=1)
|
||||
Buffers: shared hit=5
|
||||
-> Index Scan using messages_chat_id_created_at_id_idx on messages (cost=0.41..3501.16 rows=10008 width=78) (actual time=0.022..0.034 rows=51 loops=1)
|
||||
Index Cond: (chat_id = '00000000-0000-4000-8000-0000000000c0'::uuid)
|
||||
Buffers: shared hit=5
|
||||
Planning:
|
||||
Buffers: shared hit=6
|
||||
Planning Time: 0.238 ms
|
||||
Execution Time: 0.081 ms
|
||||
(9 rows)
|
||||
|
||||
=== 2. Keyset, page after message #9000
|
||||
QUERY PLAN
|
||||
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=0.41..161.20 rows=51 width=78) (actual time=0.032..0.058 rows=51 loops=1)
|
||||
Buffers: shared hit=6
|
||||
-> Index Scan using messages_chat_id_created_at_id_idx on messages (cost=0.41..646.73 rows=205 width=78) (actual time=0.030..0.048 rows=51 loops=1)
|
||||
Index Cond: ((chat_id = '00000000-0000-4000-8000-0000000000c0'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:09+00'::timestamp with time zone, 'db5c59fc-902f-4cab-9372-0af09bfd735f'::uuid)))
|
||||
Buffers: shared hit=6
|
||||
Planning Time: 0.222 ms
|
||||
Execution Time: 0.165 ms
|
||||
(7 rows)
|
||||
|
||||
=== 3. For comparison: OFFSET 9000 reads and discards all previous rows
|
||||
QUERY PLAN
|
||||
--------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=1980.85..1980.98 rows=51 width=78) (actual time=14.482..14.494 rows=51 loops=1)
|
||||
Buffers: shared hit=668
|
||||
-> Sort (cost=1958.35..1983.37 rows=10008 width=78) (actual time=13.126..13.872 rows=9051 loops=1)
|
||||
Sort Key: created_at, id
|
||||
Sort Method: quicksort Memory: 1713kB
|
||||
Buffers: shared hit=668
|
||||
-> Seq Scan on messages (cost=0.00..1293.38 rows=10008 width=78) (actual time=0.020..9.312 rows=10000 loops=1)
|
||||
Filter: (chat_id = '00000000-0000-4000-8000-0000000000c0'::uuid)
|
||||
Rows Removed by Filter: 40030
|
||||
Buffers: shared hit=668
|
||||
Planning Time: 0.151 ms
|
||||
Execution Time: 14.824 ms
|
||||
(12 rows)
|
||||
|
||||
=== 4. For comparison: keyset page #9000 without the index
|
||||
DROP INDEX
|
||||
QUERY PLAN
|
||||
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
Limit (cost=1550.36..1550.49 rows=51 width=78) (actual time=8.143..8.154 rows=51 loops=1)
|
||||
Buffers: shared hit=668
|
||||
-> Sort (cost=1550.36..1550.88 rows=205 width=78) (actual time=8.141..8.145 rows=51 loops=1)
|
||||
Sort Key: created_at, id
|
||||
Sort Method: top-N heapsort Memory: 31kB
|
||||
Buffers: shared hit=668
|
||||
-> Seq Scan on messages (cost=0.00..1543.53 rows=205 width=78) (actual time=2.383..7.810 rows=1000 loops=1)
|
||||
Filter: ((chat_id = '00000000-0000-4000-8000-0000000000c0'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:09+00'::timestamp with time zone, 'db5c59fc-902f-4cab-9372-0af09bfd735f'::uuid)))
|
||||
Rows Removed by Filter: 49030
|
||||
Buffers: shared hit=668
|
||||
Planning:
|
||||
Buffers: shared hit=4
|
||||
Planning Time: 0.280 ms
|
||||
Execution Time: 8.207 ms
|
||||
(14 rows)
|
||||
|
||||
ROLLBACK
|
||||
@@ -0,0 +1,68 @@
|
||||
# Отказы зависимостей и expiry на стенде
|
||||
# date: 2026-10-21T08:43:49Z
|
||||
# commit: 1d5c1e0 (dirty)
|
||||
|
||||
## 1. Redis остановлен: полный публичный smoke проходит через PostgreSQL
|
||||
$ docker compose stop redis
|
||||
Container messenger-lab2-redis-1 Stopping
|
||||
Container messenger-lab2-redis-1 Stopped
|
||||
|
||||
$ make test
|
||||
python3 tests/smoke.py --base-url "http://api:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
$ docker compose start redis
|
||||
Container messenger-lab2-secrets-init-1 Starting
|
||||
Container messenger-lab2-secrets-init-1 Started
|
||||
Container messenger-lab2-secrets-init-1 Waiting
|
||||
Container messenger-lab2-secrets-init-1 Exited
|
||||
Container messenger-lab2-redis-1 Starting
|
||||
Container messenger-lab2-redis-1 Started
|
||||
|
||||
## 2. PostgreSQL остановлен: ограниченный 503 без внутренних деталей
|
||||
$ docker compose stop postgres
|
||||
Container messenger-lab2-postgres-1 Stopping
|
||||
Container messenger-lab2-postgres-1 Stopped
|
||||
|
||||
$ python3 scripts/probe.py status GET /health/ready
|
||||
GET /health/ready (anonymous) -> 503 {"error": {"code": "unavailable", "message": "database unavailable", "request_id": "a7bb2a68-b382-43cd-b9da-be82a9cf1ab0"}}
|
||||
|
||||
$ python3 scripts/probe.py status GET /api/v1/chats
|
||||
GET /api/v1/chats (anonymous) -> 401 {"error": {"code": "unauthorized", "message": "missing or invalid session", "request_id": "ae589529-992e-4f89-afc9-aef87a9ea438"}}
|
||||
|
||||
$ python3 scripts/probe.py status GET /api/v1/chats Bearer unknown-token
|
||||
GET /api/v1/chats (Bearer unknown-token) -> 503 {"error": {"code": "unavailable", "message": "database unavailable", "request_id": "8f2da39f-9f7e-4416-b07b-8c0f5ebc745c"}}
|
||||
|
||||
$ docker compose start postgres
|
||||
Container messenger-lab2-secrets-init-1 Starting
|
||||
Container messenger-lab2-secrets-init-1 Started
|
||||
Container messenger-lab2-secrets-init-1 Waiting
|
||||
Container messenger-lab2-secrets-init-1 Exited
|
||||
Container messenger-lab2-postgres-1 Starting
|
||||
Container messenger-lab2-postgres-1 Started
|
||||
|
||||
$ python3 scripts/probe.py ready
|
||||
ready
|
||||
|
||||
## 3. Redis после рестарта пуст (без persistence), сессии берутся из PostgreSQL
|
||||
$ docker compose restart redis
|
||||
Container messenger-lab2-redis-1 Restarting
|
||||
Container messenger-lab2-redis-1 Started
|
||||
|
||||
$ make test
|
||||
python3 tests/smoke.py --base-url "http://api:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
## 4. Expiry: API пересоздан с SESSION_TTL_SECONDS=2
|
||||
$ docker compose exec -T api printenv SESSION_TTL_SECONDS
|
||||
2
|
||||
|
||||
$ python3 scripts/probe.py expiry 2
|
||||
register -> 201
|
||||
login -> 201 expires_at: 2026-10-21T08:44:17.766Z
|
||||
GET /api/v1/users/me (fresh) -> 200
|
||||
GET /api/v1/users/me (after 3s) -> 401
|
||||
|
||||
$ python3 scripts/probe.py ready
|
||||
ready
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# make test-persistence: restart.sh перезапускает postgres, redis, api с сохранением volumes
|
||||
# date: 2026-10-21T08:43:45Z
|
||||
# commit: 1d5c1e0 (dirty)
|
||||
|
||||
## до
|
||||
/messenger-lab2-api-1 running started=2026-10-21T08:39:28.136832991Z
|
||||
/messenger-lab2-postgres-1 running started=2026-10-21T08:39:04.138523217Z
|
||||
/messenger-lab2-redis-1 running started=2026-10-21T08:39:05.039138259Z
|
||||
|
||||
$ 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.
|
||||
|
||||
## после (started изменился у всех трёх контейнеров)
|
||||
/messenger-lab2-api-1 running started=2026-10-21T08:43:48.183944928Z
|
||||
/messenger-lab2-postgres-1 running started=2026-10-21T08:43:48.313169498Z
|
||||
/messenger-lab2-redis-1 running started=2026-10-21T08:43:48.537563303Z
|
||||
@@ -0,0 +1,12 @@
|
||||
# Публичные проверки
|
||||
# date: 2026-10-21T08:43:42Z
|
||||
# commit: 1d5c1e0 (dirty)
|
||||
|
||||
$ make check
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
|
||||
$ make test
|
||||
python3 tests/smoke.py --base-url "http://api:8080"
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
# Собственные e2e-тесты (PostgreSQL + Redis из compose.test.yaml)
|
||||
# date: 2026-10-21T08:43:08Z
|
||||
# commit: 1d5c1e0 (dirty)
|
||||
|
||||
$ docker compose -f compose.test.yaml run --rm tests npx jest --config ./test/jest-e2e.json --verbose
|
||||
Network messenger-lab2-test_default Creating
|
||||
Network messenger-lab2-test_default Created
|
||||
Container messenger-lab2-test-postgres-1 Creating
|
||||
Container messenger-lab2-test-redis-1 Creating
|
||||
Container messenger-lab2-test-redis-1 Created
|
||||
Container messenger-lab2-test-postgres-1 Created
|
||||
Container messenger-lab2-test-redis-1 Starting
|
||||
Container messenger-lab2-test-postgres-1 Starting
|
||||
Container messenger-lab2-test-redis-1 Started
|
||||
Container messenger-lab2-test-postgres-1 Started
|
||||
Prisma schema loaded from prisma/schema.prisma
|
||||
Datasource "db": PostgreSQL database "messenger_test", schema "public" at "postgres:5432"
|
||||
|
||||
2 migrations found in prisma/migrations
|
||||
|
||||
Applying migration `20261021000000_init`
|
||||
Applying migration `20261021010000_auth_sessions`
|
||||
|
||||
The following migration(s) have been applied:
|
||||
|
||||
migrations/
|
||||
└─ 20261021000000_init/
|
||||
└─ migration.sql
|
||||
└─ 20261021010000_auth_sessions/
|
||||
└─ migration.sql
|
||||
|
||||
All migrations have been successfully applied.
|
||||
PASS test/concurrency.e2e-spec.ts (8.83 s)
|
||||
Безопасность при конкурентном доступе (e2e)
|
||||
✓ принимает 100 конкурентных сообщений от 10 клиентов и сохраняет ровно 100 уникальных (736 ms)
|
||||
✓ регистрирует ровно одного пользователя при гонке 10 запросов за один и тот же username (135 ms)
|
||||
|
||||
PASS test/auth.e2e-spec.ts (8.963 s)
|
||||
Аутентификация и сессии (e2e)
|
||||
регистрация
|
||||
✓ требует password (42 ms)
|
||||
✓ отклоняет password короче 12 code points (18 ms)
|
||||
✓ хранит пароль как Argon2id-хеш, а не открытым текстом (141 ms)
|
||||
POST /api/v1/auth/sessions
|
||||
✓ выдаёт непрозрачный Bearer-токен с expires_at и пользователем (137 ms)
|
||||
✓ принимает пароль с двоеточием и не-ASCII символами (71 ms)
|
||||
✓ отвечает одинаковым 401 на неверный пароль и неизвестного пользователя (133 ms)
|
||||
✓ отвечает 401 без заголовка Authorization (3 ms)
|
||||
защищённые endpoint
|
||||
✓ не принимают Basic (81 ms)
|
||||
✓ не принимают X-User-Id сам по себе (74 ms)
|
||||
✓ игнорируют X-User-Id рядом с Bearer (151 ms)
|
||||
✓ отвечают 401 на неизвестный токен (5 ms)
|
||||
DELETE /api/v1/auth/sessions/current
|
||||
✓ отзывает только текущий токен: 204, затем 401 на повтор (112 ms)
|
||||
|
||||
[31m[Nest] 171 - [39m10/21/2026, 8:43:38 AM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mGET /health/ready -> 503: database unavailable[39m
|
||||
[31m[Nest] 171 - [39m10/21/2026, 8:43:38 AM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mGET /api/v1/chats -> 503: database unavailable[39m
|
||||
[31m[Nest] 171 - [39m10/21/2026, 8:43:38 AM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mGET /api/v1/chats -> 503: database unavailable[39m
|
||||
[31m[Nest] 171 - [39m10/21/2026, 8:43:38 AM [31m ERROR[39m [38;5;3m[HttpExceptionFilter] [39m[31mPOST /api/v1/users -> 503: database unavailable[39m
|
||||
PASS test/failures.e2e-spec.ts (11.377 s)
|
||||
Уровень 4: expiry, отказы зависимостей, rollback (e2e)
|
||||
✓ сессия истекает при коротком SESSION_TTL_SECONDS, в том числе из кэша (2770 ms)
|
||||
✓ без Redis вход, проверка сессии и logout работают через PostgreSQL (315 ms)
|
||||
✓ без PostgreSQL отвечает ограниченным 503 и не пускает анонима (239 ms)
|
||||
✓ откатывает создание чата целиком, если один из участников не существует (187 ms)
|
||||
|
||||
PASS test/api.e2e-spec.ts (11.95 s)
|
||||
API мессенджера (e2e) — граничные случаи сверх публичного smoke
|
||||
POST /api/v1/users
|
||||
✓ отклоняет некорректный JSON с кодом 400 (61 ms)
|
||||
✓ отклоняет тело с лишними полями (19 ms)
|
||||
✓ отклоняет username с заглавными буквами (5 ms)
|
||||
✓ отклоняет display_name из одних пробелов (4 ms)
|
||||
✓ отклоняет дубликат username с кодом 409 (207 ms)
|
||||
✓ никогда не возвращает поле пароля или его хэша (45 ms)
|
||||
✓ отклоняет username короче 3 символов (6 ms)
|
||||
✓ отклоняет username длиннее 32 символов (10 ms)
|
||||
✓ отклоняет username с недопустимыми символами (дефис) (4 ms)
|
||||
✓ принимает username ровно на границах длины 3 и 32 символа (64 ms)
|
||||
✓ отклоняет display_name длиннее 100 Unicode code points (3 ms)
|
||||
✓ принимает display_name ровно из 100 code points, считая эмодзи вне BMP за один символ (31 ms)
|
||||
✓ отклоняет display_name из 101 code point, состоящий из эмодзи вне BMP (4 ms)
|
||||
контроль доступа
|
||||
✓ возвращает 401 раньше 404, если и актор, и ресурс невалидны (9 ms)
|
||||
✓ возвращает 404 (не 403), когда чат запрашивает не его участник (257 ms)
|
||||
✓ отклоняет создание чата, если вызывающий не входит в member_ids (146 ms)
|
||||
✓ отклоняет создание чата с дублирующимися member_ids (63 ms)
|
||||
✓ отклоняет создание чата с неизвестным участником (73 ms)
|
||||
✓ отклоняет создание чата с пустым/пробельным title (77 ms)
|
||||
✓ возвращает 400 для синтаксически некорректного chat_id (не UUID) (78 ms)
|
||||
✓ возвращает 404 для корректного по формату, но несуществующего chat_id (69 ms)
|
||||
GET /api/v1/chats (пагинация)
|
||||
✓ использует limit=50 по умолчанию, если limit не передан (85 ms)
|
||||
✓ отклоняет нечисловой limit (73 ms)
|
||||
✓ отклоняет limit=0 (102 ms)
|
||||
✓ отклоняет cursor, не являющийся корректным base64url JSON (74 ms)
|
||||
✓ отклоняет корректно закодированный cursor с id чата, который никогда не существовал (70 ms)
|
||||
✓ обходит весь список чатов по страницам без пропусков и дублей (102 ms)
|
||||
сообщения
|
||||
✓ не принимает sender_id, переданный клиентом (141 ms)
|
||||
✓ отклоняет пустое сообщение (127 ms)
|
||||
✓ отклоняет сообщение из одних пробелов (135 ms)
|
||||
✓ отклоняет отправку в чат, где вызывающий не участник (227 ms)
|
||||
✓ отклоняет limit=0 при чтении истории (143 ms)
|
||||
✓ отклоняет limit=101 при чтении истории (138 ms)
|
||||
✓ отклоняет нечисловой limit (123 ms)
|
||||
✓ отклоняет текст сообщения длиннее 4000 Unicode code points (129 ms)
|
||||
✓ принимает текст сообщения ровно из 4000 Unicode code points (131 ms)
|
||||
✓ отклоняет текст сообщения свыше 4000 code points, состоящий из эмодзи вне BMP (128 ms)
|
||||
✓ отклоняет cursor, не являющийся корректным base64url JSON (134 ms)
|
||||
✓ отклоняет корректно закодированный cursor с id сообщения, которое никогда не существовало в этом чате (136 ms)
|
||||
✓ возвращает 400 для синтаксически некорректного chat_id при отправке сообщения (61 ms)
|
||||
✓ возвращает 400 для синтаксически некорректного chat_id при чтении истории (67 ms)
|
||||
✓ отклоняет cursor, взятый из другого чата (199 ms)
|
||||
✓ обходит всю историю по страницам без пропусков и дублей (177 ms)
|
||||
X-Request-Id
|
||||
✓ присутствует и уникален для независимых запросов (3 ms)
|
||||
✓ совпадает с request_id внутри тела ошибки (1 ms)
|
||||
|
||||
A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.
|
||||
Test Suites: 4 passed, 4 total
|
||||
Tests: 63 passed, 63 total
|
||||
Snapshots: 0 total
|
||||
Time: 13.263 s
|
||||
Ran all test suites.
|
||||
|
||||
Reference in New Issue
Block a user