From 62cb785c6398eb01b7a372a5d4bbf101f0e45015 Mon Sep 17 00:00:00 2001 From: casablanca Date: Thu, 8 Oct 2026 01:46:43 +0300 Subject: [PATCH] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D1=8B=20=D0=B0=D0=B2=D1=82=D0=BE=D0=BC=D0=B0=D1=82=D0=B8?= =?UTF-8?q?=D1=87=D0=B5=D1=81=D0=BA=D0=B8=D0=B5=20=D1=82=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D1=8B=20=D0=B0=D1=83=D1=82=D0=B5=D0=BD=D1=82=D0=B8=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0=D1=86=D0=B8=D0=B8=20=D0=B8=20=D0=BE=D1=82=D0=BA?= =?UTF-8?q?=D0=B0=D0=B7=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/test_failures.sh | 168 ++++++++++++++++++++++++++++++ scripts/test_short_ttl.sh | 51 +++++++++ tests_student/test_auth.py | 176 ++++++++++++++++++++++++++++++++ tests_student/test_short_ttl.py | 81 +++++++++++++++ 4 files changed, 476 insertions(+) create mode 100755 scripts/test_failures.sh create mode 100755 scripts/test_short_ttl.sh create mode 100644 tests_student/test_auth.py create mode 100644 tests_student/test_short_ttl.py diff --git a/scripts/test_failures.sh b/scripts/test_failures.sh new file mode 100755 index 00000000..4b1a1be0 --- /dev/null +++ b/scripts/test_failures.sh @@ -0,0 +1,168 @@ +#!/usr/bin/env bash + +set -euo pipefail + +BASE_URL="http://localhost:8080" +TOKEN_FILE=$(mktemp) + +restore_services() { + echo "Restoring PostgreSQL and Redis..." + docker compose up -d postgres redis + + echo "Waiting for API readiness..." + for attempt in $(seq 1 60); do + if curl --silent --fail \ + "$BASE_URL/health/ready" > /dev/null; then + rm -f "$TOKEN_FILE" + echo "Services restored." + return + fi + sleep 1 + done + + rm -f "$TOKEN_FILE" + echo "WARNING: API did not become ready after recovery." >&2 +} + +trap restore_services EXIT + +check_status() { + local expected="$1" + local path="$2" + local authorization="${3:-}" + + local status + + if [[ -n "$authorization" ]]; then + status=$(curl --silent --output /dev/null \ + --max-time 12 \ + --write-out "%{http_code}" \ + -H "Authorization: Bearer $authorization" \ + "$BASE_URL$path") + else + status=$(curl --silent --output /dev/null \ + --max-time 12 \ + --write-out "%{http_code}" \ + "$BASE_URL$path") + fi + + if [[ "$status" != "$expected" ]]; then + echo "FAIL: $path expected $expected, got $status" >&2 + exit 1 + fi + + echo "PASS: $path returned $status" +} + +echo "Creating a test user and session..." + +python - "$TOKEN_FILE" <<'PY' +import base64 +import json +import sys +import urllib.request +import uuid + +base = "http://localhost:8080" +username = "failure_" + uuid.uuid4().hex[:16] +password = "correct-password-123" + +def post(path, data=None, authorization=None): + headers = {} + body = None + + if data is not None: + headers["Content-Type"] = "application/json" + body = json.dumps(data).encode("utf-8") + + if authorization: + headers["Authorization"] = authorization + + request = urllib.request.Request( + base + path, + data=body, + headers=headers, + method="POST", + ) + + with urllib.request.urlopen(request, timeout=10) as response: + assert response.status == 201 + return json.load(response) + +post("/api/v1/users", { + "username": username, + "display_name": "Failure Test User", + "password": password, +}) + +credentials = base64.b64encode( + f"{username}:{password}".encode() +).decode() + +result = post( + "/api/v1/auth/sessions", + authorization=f"Basic {credentials}", +) + +with open(sys.argv[1], "w", encoding="utf-8") as file: + file.write(result["token"]) + +print("Test session created.") +PY + +TOKEN=$(cat "$TOKEN_FILE") + +echo +echo "Checking baseline..." +check_status 200 "/health/live" +check_status 200 "/health/ready" +check_status 200 "/api/v1/users/me" "$TOKEN" + +echo +echo "=== Redis failure ===" + +docker compose stop redis + +check_status 200 "/health/live" +check_status 503 "/health/ready" +check_status 503 "/api/v1/users/me" "$TOKEN" + +echo "Restarting Redis..." +docker compose start redis + +for attempt in $(seq 1 60); do + if curl --silent --fail \ + "$BASE_URL/health/ready" > /dev/null; then + break + fi + sleep 1 +done + +check_status 200 "/health/ready" +check_status 200 "/api/v1/users/me" "$TOKEN" + +echo +echo "=== PostgreSQL failure ===" + +docker compose stop postgres + +check_status 200 "/health/live" +check_status 503 "/health/ready" +check_status 503 "/api/v1/users/me" "$TOKEN" + +echo "Restarting PostgreSQL..." +docker compose start postgres + +for attempt in $(seq 1 60); do + if curl --silent --fail \ + "$BASE_URL/health/ready" > /dev/null; then + break + fi + sleep 1 +done + +check_status 200 "/health/ready" +check_status 200 "/api/v1/users/me" "$TOKEN" + +echo +echo "PASS: dependency failure and recovery tests completed." \ No newline at end of file diff --git a/scripts/test_short_ttl.sh b/scripts/test_short_ttl.sh new file mode 100755 index 00000000..6723184b --- /dev/null +++ b/scripts/test_short_ttl.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash + +set -euo pipefail + +restore_api() { + echo "Restoring API with SESSION_TTL_SECONDS=3600..." + + SESSION_TTL_SECONDS=3600 \ + docker compose up -d --force-recreate --no-deps api +} + +trap restore_api EXIT + +echo "Starting API with SESSION_TTL_SECONDS=2..." + +SESSION_TTL_SECONDS=2 \ + docker compose up -d --force-recreate --no-deps api + +echo "Checking API configuration..." + +actual_ttl=$(docker compose exec -T api printenv SESSION_TTL_SECONDS) + +if [[ "$actual_ttl" != "2" ]]; then + echo "Expected SESSION_TTL_SECONDS=2, got $actual_ttl" >&2 + exit 1 +fi + +echo "Waiting for API readiness..." + +ready=false + +for attempt in $(seq 1 30); do + if curl --silent --fail \ + http://localhost:8080/health/ready > /dev/null; then + ready=true + break + fi + + sleep 1 +done + +if [[ "$ready" != "true" ]]; then + echo "API did not become ready." >&2 + exit 1 +fi + +echo "Running short TTL test..." + +python tests_student/test_short_ttl.py + +echo "PASS: short session TTL test completed." \ No newline at end of file diff --git a/tests_student/test_auth.py b/tests_student/test_auth.py new file mode 100644 index 00000000..3d81a635 --- /dev/null +++ b/tests_student/test_auth.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 + +import base64 +import json +import urllib.error +import urllib.request +import uuid + + +BASE_URL = "http://localhost:8080" +PASSWORD = "correct-password-123" + + +def call( + method: str, + path: str, + body: dict | None = None, + headers: dict[str, str] | None = None, +) -> tuple[int, dict | None, dict]: + request_headers = dict(headers or {}) + + data = None + if body is not None: + data = json.dumps(body).encode("utf-8") + request_headers["Content-Type"] = "application/json" + + request = urllib.request.Request( + BASE_URL + path, + data=data, + headers=request_headers, + method=method, + ) + + try: + with urllib.request.urlopen(request, timeout=10) as response: + raw = response.read() + response_body = json.loads(raw) if raw else None + return response.status, response_body, dict(response.headers) + except urllib.error.HTTPError as error: + raw = error.read() + response_body = json.loads(raw) if raw else None + return error.code, response_body, dict(error.headers) + + +def basic_header(username: str, password: str) -> str: + credentials = f"{username}:{password}".encode("utf-8") + encoded = base64.b64encode(credentials).decode("ascii") + return f"Basic {encoded}" + + +def main() -> None: + username = "auth_" + uuid.uuid4().hex[:16] + + # 1. Создаём отдельного пользователя для этого теста. + status, body, _ = call( + "POST", + "/api/v1/users", + { + "username": username, + "display_name": "Auth Test User", + "password": PASSWORD, + }, + ) + + if status != 201: + raise AssertionError( + f"registration: expected 201, got {status}: {body}" + ) + + # 2. Неверный пароль не должен создавать сессию. + status, body, headers = call( + "POST", + "/api/v1/auth/sessions", + headers={ + "Authorization": basic_header( + username, + "definitely-wrong-password", + ) + }, + ) + + if status != 401: + raise AssertionError( + f"wrong password: expected 401, got {status}: {body}" + ) + + if body is None or body.get("error", {}).get("code") != "unauthorized": + raise AssertionError( + f"wrong password: unexpected response body: {body}" + ) + + # 3. С правильным паролем получаем Bearer-сессию. + status, body, _ = call( + "POST", + "/api/v1/auth/sessions", + headers={ + "Authorization": basic_header(username, PASSWORD) + }, + ) + + if status != 201: + raise AssertionError( + f"login: expected 201, got {status}: {body}" + ) + + if body is None: + raise AssertionError("login: empty response body") + + token = body.get("token") + + if not token: + raise AssertionError("login: token is missing") + + if body.get("token_type") != "Bearer": + raise AssertionError( + f"login: expected token_type Bearer, got {body.get('token_type')}" + ) + + bearer = {"Authorization": f"Bearer {token}"} + + # 4. До logout токен обязан работать. + status, body, _ = call( + "GET", + "/api/v1/users/me", + headers=bearer, + ) + + if status != 200: + raise AssertionError( + f"token before logout: expected 200, got {status}: {body}" + ) + + # 5. Отзываем текущую сессию. + status, body, _ = call( + "DELETE", + "/api/v1/auth/sessions/current", + headers=bearer, + ) + + if status != 204: + raise AssertionError( + f"logout: expected 204, got {status}: {body}" + ) + + # 6. Тот же токен после logout больше не принимается. + status, body, _ = call( + "GET", + "/api/v1/users/me", + headers=bearer, + ) + + if status != 401: + raise AssertionError( + f"token after logout: expected 401, got {status}: {body}" + ) + + # 7. Повторный logout с уже отозванным токеном тоже не авторизован. + status, body, _ = call( + "DELETE", + "/api/v1/auth/sessions/current", + headers=bearer, + ) + + if status != 401: + raise AssertionError( + f"repeated logout: expected 401, got {status}: {body}" + ) + + print( + "PASS: wrong password returned 401; " + "valid session worked; logout revoked the token." + ) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/tests_student/test_short_ttl.py b/tests_student/test_short_ttl.py new file mode 100644 index 00000000..3f469bb9 --- /dev/null +++ b/tests_student/test_short_ttl.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 + +import base64 +import json +import time +import urllib.error +import urllib.request +import uuid + + +BASE_URL = "http://localhost:8080" +PASSWORD = "correct-password-123" + + +def call(method, path, body=None, headers=None): + request_headers = dict(headers or {}) + data = None + + if body is not None: + data = json.dumps(body).encode("utf-8") + request_headers["Content-Type"] = "application/json" + + request = urllib.request.Request( + BASE_URL + path, + data=data, + headers=request_headers, + method=method, + ) + + try: + with urllib.request.urlopen(request, timeout=10) as response: + raw = response.read() + return response.status, json.loads(raw) if raw else None + except urllib.error.HTTPError as error: + raw = error.read() + return error.code, json.loads(raw) if raw else None + + +def main(): + username = "ttl_" + uuid.uuid4().hex[:16] + + status, body = call( + "POST", + "/api/v1/users", + { + "username": username, + "display_name": "TTL Test User", + "password": PASSWORD, + }, + ) + assert status == 201, f"registration: {status}, {body}" + + credentials = base64.b64encode( + f"{username}:{PASSWORD}".encode("utf-8") + ).decode("ascii") + + status, body = call( + "POST", + "/api/v1/auth/sessions", + headers={"Authorization": f"Basic {credentials}"}, + ) + assert status == 201, f"login: {status}, {body}" + + token = body["token"] + bearer = {"Authorization": f"Bearer {token}"} + + status, body = call("GET", "/api/v1/users/me", headers=bearer) + assert status == 200, f"before expiry: {status}, {body}" + + print("PASS: token works immediately after login.") + + time.sleep(4) + + status, body = call("GET", "/api/v1/users/me", headers=bearer) + assert status == 401, f"after expiry: {status}, {body}" + + print("PASS: expired token returned 401.") + + +if __name__ == "__main__": + main() \ No newline at end of file