# Перейти в папку проекта и создать .env (один раз) cd C:\Users\79152\Desktop\mtusi2026lab2 copy .env.example .env ------------------------------------------------------------ # Запуск: API + PostgreSQL + Redis docker compose --env-file .env config --quiet docker compose --env-file .env up -d --build docker compose ps ------------------------------------------------------------ # Миграции: применились при старте, повтор ничего не дублирует docker compose logs api --tail 15 docker compose exec api python -m app.migrate docker compose exec postgres psql -U messenger -d messenger -c "\dt" docker compose exec postgres psql -U messenger -d messenger -c "SELECT * FROM schema_migrations" ------------------------------------------------------------ # Функции: St печатает код ответа, Login входит через Basic (вставить один раз) function St($m,$u,$b,$h){ try{ if($b){ $r=Invoke-WebRequest $u -Method $m -ContentType 'application/json' -Body $b -Headers $h -UseBasicParsing } else { $r=Invoke-WebRequest $u -Method $m -Headers $h -UseBasicParsing }; $r.StatusCode } catch { $_.Exception.Response.StatusCode.value__ } } function Login($u,$p){ $b=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("${u}:${p}")); Invoke-RestMethod http://localhost:8080/api/v1/auth/sessions -Method Post -Headers @{ Authorization = "Basic $b" } } ------------------------------------------------------------ # Health Invoke-RestMethod http://localhost:8080/health/live Invoke-RestMethod http://localhost:8080/health/ready ------------------------------------------------------------ # Суффикс для уникальных имён и общий пароль $s = Get-Random -Maximum 100000 $PW = 'Hockey-pass-2026' ------------------------------------------------------------ # Регистрация: Майк, Артём, Толя (пароля в ответе нет) $mike = Invoke-RestMethod http://localhost:8080/api/v1/users -Method Post -ContentType application/json -Body "{""username"":""mike_$s"",""display_name"":""Mike"",""password"":""$PW""}"; $M = $mike.id; $mike $artem = Invoke-RestMethod http://localhost:8080/api/v1/users -Method Post -ContentType application/json -Body "{""username"":""artem_$s"",""display_name"":""Artem"",""password"":""$PW""}"; $A = $artem.id; $artem $toly = Invoke-RestMethod http://localhost:8080/api/v1/users -Method Post -ContentType application/json -Body "{""username"":""toly_$s"",""display_name"":""Toly"",""password"":""$PW""}"; $T = $toly.id; $toly ------------------------------------------------------------ # Вход (Basic) -> получаем Bearer-токены $sm = Login "mike_$s" $PW; $sm | ConvertTo-Json -Depth 5 $sa = Login "artem_$s" $PW $st = Login "toly_$s" $PW $hM = @{ Authorization = "Bearer $($sm.token)" } $hA = @{ Authorization = "Bearer $($sa.token)" } $hT = @{ Authorization = "Bearer $($st.token)" } ------------------------------------------------------------ # Кто я (по Bearer) Invoke-RestMethod http://localhost:8080/api/v1/users/me -Headers $hM ------------------------------------------------------------ # Майк создаёт чат с Артёмом $body = "{""title"":""Hockey"",""member_ids"":[""$M"",""$A""]}"; $chat = Invoke-RestMethod http://localhost:8080/api/v1/chats -Method Post -ContentType application/json -Body $body -Headers $hM; $CHAT = $chat.id; $chat ------------------------------------------------------------ # Переписка: Артём, Майк, Артём Invoke-RestMethod http://localhost:8080/api/v1/chats/$CHAT/messages -Method Post -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes('{"text":"Привет"}')) -Headers $hA Invoke-RestMethod http://localhost:8080/api/v1/chats/$CHAT/messages -Method Post -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes('{"text":"Привет, как дела?"}')) -Headers $hM Invoke-RestMethod http://localhost:8080/api/v1/chats/$CHAT/messages -Method Post -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes('{"text":"Хорошо, идём на тренировку?"}')) -Headers $hA ------------------------------------------------------------ # История чата и список чатов Invoke-RestMethod "http://localhost:8080/api/v1/chats/$CHAT/messages" -Headers $hM | ConvertTo-Json -Depth 5 Invoke-RestMethod "http://localhost:8080/api/v1/chats" -Headers $hA | ConvertTo-Json -Depth 5 ------------------------------------------------------------ # Пагинация по курсору $p = Invoke-RestMethod "http://localhost:8080/api/v1/chats/$CHAT/messages?limit=2" -Headers $hM; $p | ConvertTo-Json -Depth 5; $C = [uri]::EscapeDataString($p.next_cursor) Invoke-RestMethod "http://localhost:8080/api/v1/chats/$CHAT/messages?limit=2&cursor=$C" -Headers $hM | ConvertTo-Json -Depth 5 ------------------------------------------------------------ # Ошибки аутентификации: все 401, кроме последней строки $bad = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("mike_${s}:wrong-password-1")) $good = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("mike_${s}:$PW")) "nevernyy parol: " + (St POST "http://localhost:8080/api/v1/auth/sessions" $null @{ Authorization = "Basic $bad" }) "bez tokena: " + (St GET "http://localhost:8080/api/v1/users/me" $null @{}) "Basic na /users/me: " + (St GET "http://localhost:8080/api/v1/users/me" $null @{ Authorization = "Basic $good" }) "tolko X-User-Id: " + (St GET "http://localhost:8080/api/v1/users/me" $null @{ "X-User-Id" = $M }) "poddelnyy token: " + (St GET "http://localhost:8080/api/v1/users/me" $null @{ Authorization = "Bearer fake-token-123" }) (Invoke-RestMethod http://localhost:8080/api/v1/users/me -Headers @{ Authorization = "Bearer $($sm.token)"; "X-User-Id" = $T }).username ------------------------------------------------------------ # Ошибки доступа и данных: 404 / 400 / 400 / 409 "Tolya v chuzhom chate: " + (St GET "http://localhost:8080/api/v1/chats/$CHAT/messages" $null $hT) "pustoy tekst: " + (St POST "http://localhost:8080/api/v1/chats/$CHAT/messages" '{"text":" "}' $hM) "korotkiy parol: " + (St POST "http://localhost:8080/api/v1/users" "{""username"":""short_$s"",""display_name"":""S"",""password"":""123""}" @{}) "dubl username: " + (St POST "http://localhost:8080/api/v1/users" "{""username"":""mike_$s"",""display_name"":""Other"",""password"":""$PW""}" @{}) ------------------------------------------------------------ # Что лежит в БД: хэш Argon2id вместо пароля, хэш токена вместо токена docker compose exec postgres psql -U messenger -d messenger -c "SELECT username, left(password_hash, 40) AS hash FROM users ORDER BY created_at DESC LIMIT 3" docker compose exec postgres psql -U messenger -d messenger -c "SELECT left(encode(token_hash,'hex'),16) AS token_sha256, expires_at, revoked_at FROM sessions ORDER BY created_at DESC LIMIT 3" ------------------------------------------------------------ # Redis: кэш сессий с TTL Invoke-RestMethod http://localhost:8080/api/v1/users/me -Headers $hA | Out-Null docker compose exec redis redis-cli --scan --pattern "sess:*" $k = docker compose exec -T redis redis-cli --scan --pattern "sess:*" | Select-Object -First 1 docker compose exec redis redis-cli TTL $k ------------------------------------------------------------ # Logout Майка: 204, потом его токен 401 "logout: " + (St DELETE "http://localhost:8080/api/v1/auth/sessions/current" $null $hM) "token posle logout: " + (St GET "http://localhost:8080/api/v1/users/me" $null $hM) "povtornyy logout: " + (St DELETE "http://localhost:8080/api/v1/auth/sessions/current" $null $hM) ------------------------------------------------------------ # Ручной рестарт API + PostgreSQL + Redis: токен Артёма и история на месте docker compose restart postgres redis api docker compose ps Invoke-RestMethod http://localhost:8080/health/ready Invoke-RestMethod "http://localhost:8080/api/v1/chats/$CHAT/messages" -Headers $hA | ConvertTo-Json -Depth 5 ------------------------------------------------------------ # Публичные тесты python scripts\check_contract.py python tests\smoke.py --base-url http://localhost:8080 ------------------------------------------------------------ # Тест сохранности (persistence) python tests\resilience.py --mode persistence --action-script scripts\restart.cmd --base-url http://localhost:8080 docker compose ps ------------------------------------------------------------ # Свои тесты: аутентификация, logout, гонка регистрации, ошибки, пагинация python student-tests\run.py --base-url http://localhost:8080 ------------------------------------------------------------ # Гонка: 10 клиентов x 10 сообщений python student-tests\race.py --base-url http://localhost:8080 ------------------------------------------------------------ # Истечение сессии: второй API с TTL = 2 секунды docker compose --env-file .env --profile ttl up -d api-ttl python student-tests\expiry.py --base-url http://localhost:8081 docker compose --profile ttl stop api-ttl ------------------------------------------------------------ # Отказ Redis и PostgreSQL python student-tests\outage.py --base-url http://localhost:8080 ------------------------------------------------------------ # Rollback создания чата docker compose cp student-tests/rollback_check.py api:/tmp/rollback_check.py docker compose exec api python /tmp/rollback_check.py ------------------------------------------------------------ # EXPLAIN истории на 60 000 сообщений docker compose cp student-tests/explain.sql postgres:/tmp/explain.sql docker compose exec postgres psql -U messenger -d messenger -f /tmp/explain.sql ------------------------------------------------------------ # Нагрузка (по желанию) python tests\load.py --base-url http://localhost:8080 --duration 15 --concurrency 4 ------------------------------------------------------------ # Остановка (данные в volume сохраняются) docker compose down