#!/usr/bin/env python3 """Собственные проверки lab2 (оценка 4): auth, гонки, expiry, отказ Redis/DB.""" import base64 import os import subprocess import threading import time import uuid from concurrent.futures import ThreadPoolExecutor from pathlib import Path from urllib.parse import quote from client import Client, Failure, arguments, check, run ROOT = Path(__file__).resolve().parents[1] def _password(): return "T3st-" + uuid.uuid4().hex def test_invalid_json(c: Client): resp = c.call( "POST", "/api/v1/users", 400, raw=b"{not-json", headers={"Content-Type": "application/json"}, schema="Error", ) check(resp["json"]["error"]["code"] == "invalid_request", "expected invalid_request for bad JSON") def test_wrong_password(c: Client): alice = c.user("wp") bad = base64.b64encode( (alice["registration"]["username"] + ":wrong-password-xx").encode() ).decode() resp = c.call( "POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + bad}, schema="Error", ) check(resp["json"]["error"]["code"] == "unauthorized", "wrong password must be 401") check( resp["headers"].get("WWW-Authenticate", "").lower().startswith("basic"), "WWW-Authenticate Basic required", ) def test_logout(c: Client): alice = c.user("lo") c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice) c.call("GET", "/api/v1/users/me", 401, actor=alice, schema="Error") def test_duplicate_username(c: Client): name = "dup_" + uuid.uuid4().hex[:10] password = _password() body = {"username": name, "display_name": "Один", "password": password} c.call("POST", "/api/v1/users", 201, body=body, schema="User") resp = c.call("POST", "/api/v1/users", 409, body=body, schema="Error") check(resp["json"]["error"]["code"] == "conflict", "expected conflict") def test_username_race(c: Client): """Гонка регистрации одинакового username → ровно один 201, остальные 409.""" name = "race_" + uuid.uuid4().hex[:10] password = _password() body = {"username": name, "display_name": "Гонка", "password": password} barrier = threading.Barrier(8) results = [] def worker(): local = Client(c.base, timeout=20) barrier.wait() try: resp = local.call("POST", "/api/v1/users", [201, 409], body=body) results.append(resp["status"]) except Failure as exc: results.append(str(exc)) with ThreadPoolExecutor(max_workers=8) as pool: list(pool.map(lambda _: worker(), range(8))) ok = [r for r in results if r == 201] conflicted = [r for r in results if r == 409] check(len(ok) == 1, "expected exactly one successful registration, got %r" % (results,)) check(len(conflicted) == 7, "expected seven conflicts, got %r" % (results,)) def test_foreign_chat(c: Client): alice = c.user("own_a") eve = c.user("own_e") chat = c.call( "POST", "/api/v1/chats", 201, actor=alice, body={"title": "Секрет", "member_ids": [alice["id"]]}, schema="Chat", )["json"] path = "/api/v1/chats/" + chat["id"] c.call("GET", path, 404, actor=eve, schema="Error") c.call("GET", path + "/messages", 404, actor=eve, schema="Error") c.call("POST", path + "/messages", 404, actor=eve, body={"text": "взлом"}, schema="Error") def test_empty_message(c: Client): alice = c.user("own_empty") chat = c.call( "POST", "/api/v1/chats", 201, actor=alice, body={"title": "Тест", "member_ids": [alice["id"]]}, schema="Chat", )["json"] for text in ("", " ", "\n\t"): resp = c.call( "POST", "/api/v1/chats/" + chat["id"] + "/messages", 400, actor=alice, body={"text": text}, schema="Error", ) check(resp["json"]["error"]["code"] == "invalid_request", "empty text must be 400") def test_pagination_pages(c: Client): alice = c.user("page_a") chat = c.call( "POST", "/api/v1/chats", 201, actor=alice, body={"title": "Страницы", "member_ids": [alice["id"]]}, schema="Chat", )["json"] created = [] for i in range(5): created.append(c.message(alice, chat, "msg-%d" % i)["json"]) path = "/api/v1/chats/" + chat["id"] + "/messages" collected = [] cursor = None pages = 0 while True: q = path + "?limit=2" if cursor: q += "&cursor=" + quote(cursor, safe="") page = c.call("GET", q, actor=alice, schema="MessagePage")["json"] pages += 1 collected.extend(page["items"]) cursor = page["next_cursor"] if cursor is None: break check(pages >= 3, "expected several pages with limit=2 over 5 messages") check(len(collected) == 5, "pagination must return all messages once") from client import timestamp expected = sorted(created, key=lambda m: (timestamp(m["created_at"]), uuid.UUID(m["id"]).int)) check(collected == expected, "pagination must return keyset order") def test_session_expiry(c: Client): """Без schema-валидации клиента: иначе OpenAPI-parse съедает короткий TTL.""" import json import urllib.error import urllib.request ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) if ttl > 5: print("SKIP expiry: set SESSION_TTL_SECONDS<=5 on server and re-run") return username = "ttl_" + uuid.uuid4().hex[:10] password = _password() body = json.dumps( {"username": username, "display_name": "TTL", "password": password} ).encode() req = urllib.request.Request( c.base + "/api/v1/users", data=body, headers={"Content-Type": "application/json", "Accept": "application/json"}, method="POST", ) with urllib.request.urlopen(req, timeout=30) as resp: check(resp.status == 201, "register for expiry") cred = base64.b64encode((username + ":" + password).encode()).decode() req = urllib.request.Request( c.base + "/api/v1/auth/sessions", data=b"", headers={"Authorization": "Basic " + cred, "Accept": "application/json"}, method="POST", ) with urllib.request.urlopen(req, timeout=30) as resp: session = json.loads(resp.read()) token = session["token"] req = urllib.request.Request( c.base + "/api/v1/users/me", headers={"Authorization": "Bearer " + token, "Accept": "application/json"}, ) with urllib.request.urlopen(req, timeout=10) as resp: check(resp.status == 200, "session must work before expiry") time.sleep(ttl + 1.5) try: urllib.request.urlopen(req, timeout=10) raise Failure("session still valid after TTL") except urllib.error.HTTPError as exc: check(exc.code == 401, "expected 401 after TTL, got %s" % exc.code) print("PASS: session expired after TTL=%d" % ttl) def _compose(*args: str) -> None: cmd = ["docker", "compose", "--env-file", str(ROOT / ".env"), "-f", str(ROOT / "compose.yaml"), *args] subprocess.check_call(cmd, cwd=str(ROOT), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def test_redis_down_recovers(c: Client): """При недоступности Redis — 503, без «анонимного» доверия; после старта снова ready.""" try: _compose("stop", "redis") except (subprocess.CalledProcessError, FileNotFoundError) as exc: print("SKIP redis-down: docker compose unavailable (%s)" % exc) return try: deadline = time.monotonic() + 30 saw_503 = False while time.monotonic() < deadline: try: c.call("GET", "/health/ready", 503, schema="Error") saw_503 = True break except Failure: time.sleep(0.5) check(saw_503, "ready must become 503 when redis is down") alice = None # Protected path must not succeed as anonymous / must not 200. try: # Re-login impossible without redis; any bearer must fail closed. c.call( "GET", "/api/v1/users/me", [401, 503], headers={"Authorization": "Bearer deadbeefdeadbeefdeadbeefdeadbeef"}, schema="Error", ) except Failure as exc: raise Failure("protected endpoint must fail closed when redis down: %s" % exc) from exc finally: _compose("start", "redis") deadline = time.monotonic() + 60 while True: try: c.call("GET", "/health/ready", schema="Health") break except Failure: check(time.monotonic() < deadline, "stack did not recover after redis start") time.sleep(0.5) print("PASS: redis down -> 503, then recovery") def test_concurrency_100(c: Client): alice = c.user("race_a") bob = c.user("race_b") chat = c.call( "POST", "/api/v1/chats", 201, actor=alice, body={"title": "Гонка", "member_ids": [alice["id"], bob["id"]]}, schema="Chat", )["json"] barrier = threading.Barrier(10) errors = [] def worker(worker_id: int): local = Client(c.base, timeout=20) actor = alice if worker_id % 2 == 0 else bob barrier.wait() for i in range(10): try: local.message(actor, chat, "race-%d-%d" % (worker_id, i)) except Failure as exc: errors.append(str(exc)) with ThreadPoolExecutor(max_workers=10) as pool: list(pool.map(worker, range(10))) check(not errors, "concurrency errors: " + "; ".join(errors[:3])) path = "/api/v1/chats/" + chat["id"] + "/messages" collected = [] cursor = None while True: q = path + "?limit=100" if cursor: q += "&cursor=" + quote(cursor, safe="") page = c.call("GET", q, actor=alice, schema="MessagePage")["json"] collected.extend(page["items"]) cursor = page["next_cursor"] if cursor is None: break check(len(collected) == 100, "expected 100 messages, got %d" % len(collected)) check(len(set(m["id"] for m in collected)) == 100, "expected 100 unique ids") def main(): args = arguments("Own lab2 tests: auth, races, expiry, redis failure") c = Client(args.base_url, args.ca_file, timeout=20) c.call("GET", "/health/ready", schema="Health") test_invalid_json(c) print("PASS: invalid JSON") test_wrong_password(c) print("PASS: wrong password") test_logout(c) print("PASS: logout") test_duplicate_username(c) print("PASS: duplicate username") test_username_race(c) print("PASS: username registration race") test_foreign_chat(c) print("PASS: foreign chat -> 404") test_empty_message(c) print("PASS: empty message") test_pagination_pages(c) print("PASS: multi-page pagination") test_concurrency_100(c) print("PASS: concurrency 100") test_session_expiry(c) test_redis_down_recovers(c) print("PASS: all own lab2 tests") if __name__ == "__main__": run(main)