From 14ec6273414a78d1a90a869a40bfcc272256a282 Mon Sep 17 00:00:00 2001 From: Maksimova Snezhana Date: Thu, 1 Oct 2026 02:57:49 +0300 Subject: [PATCH] =?UTF-8?q?rollback-=D1=82=D0=B5=D1=81=D1=82=D1=8B=20?= =?UTF-8?q?=D0=BD=D0=B0=20urllib=20=D0=B8=D0=B7-=D0=B7=D0=B0=20=D0=BD?= =?UTF-8?q?=D0=B5=D1=81=D1=82=D0=B0=D0=B1=D0=B8=D0=BB=D1=8C=D0=BD=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D0=B8=20httpx=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20d?= =?UTF-8?q?ocker-proxy=20=D0=BD=D0=B0=20win?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/auth.py | 8 ++- app/repositories/chats.py | 34 ++++++---- scripts/restart.cmd | 4 ++ student-tests/test_rollback.py | 109 ++++++++++++++++++++------------- 4 files changed, 97 insertions(+), 58 deletions(-) create mode 100644 scripts/restart.cmd diff --git a/app/auth.py b/app/auth.py index 8535d73..4983698 100644 --- a/app/auth.py +++ b/app/auth.py @@ -16,7 +16,7 @@ SESSION_TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600")) def _prehash(password: str) -> bytes: # bcrypt работает с ≤72 байт, SHA-256 даёт 32 байта и снимает ограничение - return hashlib.sha256(password.encode("utf-8")).digest() + return hashlib.sha256(password.encode("utf-8")).hexdigest().encode("ascii") def hash_password(password: str) -> str: @@ -72,7 +72,9 @@ async def revoke_current_session(authorization: str, db: AsyncSession) -> None: if not authorization or not authorization.startswith("Bearer "): raise _unauthorized_bearer() token = authorization[7:] - await db.execute( + result = await db.execute( delete(SessionRow).where(SessionRow.token_hash == hash_token(token)) ) - await db.commit() \ No newline at end of file + await db.commit() + if result.rowcount == 0: + raise _unauthorized_bearer() \ No newline at end of file diff --git a/app/repositories/chats.py b/app/repositories/chats.py index a1b6009..44fe964 100644 --- a/app/repositories/chats.py +++ b/app/repositories/chats.py @@ -10,20 +10,28 @@ from ..db.models import Chat, ChatMember, User async def create_atomic( db: AsyncSession, title: str, member_ids: list[UUID] ) -> Chat: - async with db.begin(): - found = ( - (await db.execute(select(User.id).where(User.id.in_(member_ids)))) - .scalars() - .all() - ) - if len(set(found)) != len(set(member_ids)): - raise ValueError("member_not_found") + # проверка всех участников + found = ( + (await db.execute(select(User.id).where(User.id.in_(member_ids)))) + .scalars() + .all() + ) + if len(set(found)) != len(set(member_ids)): + await db.rollback() + raise ValueError("member_not_found") - chat = Chat(title=title) - db.add(chat) - await db.flush() - for uid in member_ids: - db.add(ChatMember(chat_id=chat.id, user_id=uid)) + chat = Chat(title=title) + db.add(chat) + await db.flush() # получить chat.id + + for uid in member_ids: + db.add(ChatMember(chat_id=chat.id, user_id=uid)) + + try: + await db.commit() + except Exception: + await db.rollback() + raise await db.refresh(chat) return chat diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 0000000..d329b24 --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,4 @@ +@echo off +docker compose restart api +docker compose restart postgres +docker compose restart redis \ No newline at end of file diff --git a/student-tests/test_rollback.py b/student-tests/test_rollback.py index 45d3547..a83bbf2 100644 --- a/student-tests/test_rollback.py +++ b/student-tests/test_rollback.py @@ -1,61 +1,86 @@ import asyncio import base64 +import json +import urllib.error +import urllib.request import uuid -import httpx import pytest BASE = "http://127.0.0.1:8080" PASSWORD = "Example-only-not-a-real-secret-123" -async def _create_user(c, name): - return await c.post( - "/api/v1/users", - json={"username": name, "display_name": name, "password": PASSWORD}, +def _post(path, body, token=None): + h = {"Content-Type": "application/json", "Accept": "application/json"} + if token: + h["Authorization"] = f"Bearer {token}" + data = json.dumps(body).encode("utf-8") + req = urllib.request.Request(BASE + path, data=data, method="POST", headers=h) + try: + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + payload = e.read() + try: + return e.code, json.loads(payload) if payload else None + except ValueError: + return e.code, None + + +def _post_basic(path, username, password): + cred = base64.b64encode(f"{username}:{password}".encode()).decode() + req = urllib.request.Request( + BASE + path, method="POST", + headers={"Authorization": f"Basic {cred}", "Accept": "application/json"}, ) + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, json.loads(r.read()) -async def _login(c, name): - cred = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode() - r = await c.post( - "/api/v1/auth/sessions", headers={"Authorization": f"Basic {cred}"} - ) - return r.json()["token"] +def _create_user(name): + return _post("/api/v1/users", { + "username": name, "display_name": name, "password": PASSWORD, + }) -@pytest.mark.asyncio -async def test_duplicate_username_race(): - async with httpx.AsyncClient(base_url=BASE, timeout=10) as c: - name = f"dup_{uuid.uuid4().hex[:8]}" - r1, r2 = await asyncio.gather(_create_user(c, name), _create_user(c, name)) - codes = sorted([r1.status_code, r2.status_code]) - assert codes == [201, 409], codes +def _login(name): + _, body = _post_basic("/api/v1/auth/sessions", name, PASSWORD) + return body["token"] -@pytest.mark.asyncio -async def test_chat_with_unknown_member_rolls_back(): - async with httpx.AsyncClient(base_url=BASE, timeout=10) as c: - name = f"cb_{uuid.uuid4().hex[:8]}" - me = (await _create_user(c, name)).json() - tok = await _login(c, name) - r = await c.post( - "/api/v1/chats", - json={"title": "x", "member_ids": [me["id"], str(uuid.uuid4())]}, - headers={"Authorization": f"Bearer {tok}"}, - ) - assert r.status_code == 404 +def test_duplicate_username_race(): + name = f"dup_{uuid.uuid4().hex[:8]}" + + import threading + results = [None, None] + + def worker(i): + results[i] = _create_user(name) + + t1 = threading.Thread(target=worker, args=(0,)) + t2 = threading.Thread(target=worker, args=(1,)) + t1.start(); t2.start() + t1.join(); t2.join() + + codes = sorted([results[0][0], results[1][0]]) + assert codes == [201, 409], codes -@pytest.mark.asyncio -async def test_message_to_missing_chat(): - async with httpx.AsyncClient(base_url=BASE, timeout=10) as c: - name = f"mc_{uuid.uuid4().hex[:8]}" - await _create_user(c, name) - tok = await _login(c, name) - r = await c.post( - f"/api/v1/chats/{uuid.uuid4()}/messages", - json={"text": "hi"}, - headers={"Authorization": f"Bearer {tok}"}, - ) - assert r.status_code == 404 \ No newline at end of file +def test_chat_with_unknown_member_rolls_back(): + name = f"cb_{uuid.uuid4().hex[:8]}" + s, me = _create_user(name) + assert s == 201, me + tok = _login(name) + s, _ = _post("/api/v1/chats", { + "title": "x", "member_ids": [me["id"], str(uuid.uuid4())], + }, token=tok) + assert s == 404 + + +def test_message_to_missing_chat(): + name = f"mc_{uuid.uuid4().hex[:8]}" + _create_user(name) + tok = _login(name) + s, _ = _post(f"/api/v1/chats/{uuid.uuid4()}/messages", {"text": "hi"}, token=tok) + assert s == 404 \ No newline at end of file