From 509161edcabe7f99a67d9a3fbd3c35ae077d9cd4 Mon Sep 17 00:00:00 2001 From: Sergey Lyakhonov Date: Fri, 9 Oct 2026 14:25:02 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A3=D1=82=D0=BE=D1=87=D0=BD=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=BF=D0=BE=D1=80=D1=8F=D0=B4=D0=BE=D0=BA=20=D0=B0=D1=83=D1=82?= =?UTF-8?q?=D0=B5=D0=BD=D1=82=D0=B8=D1=84=D0=B8=D0=BA=D0=B0=D1=86=D0=B8?= =?UTF-8?q?=D0=B8=20=D0=B8=20=D0=BF=D0=BE=D0=B4=D1=82=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=B4=D0=B8=D0=BB=20=D0=B8=D1=82=D0=BE=D0=B3=D0=BE=D0=B2=D1=8B?= =?UTF-8?q?=D0=B5=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- evidence/final_checks.json | 86 ++++++++++++++++++++++++++++++++++++++ scripts/wait_ready.py | 17 ++++++++ src/routes/chats.py | 11 ++--- src/routes/common.py | 2 +- src/routes/messages.py | 8 ++-- student-tests/test_lab2.py | 4 ++ 6 files changed, 115 insertions(+), 13 deletions(-) create mode 100644 evidence/final_checks.json create mode 100644 scripts/wait_ready.py diff --git a/evidence/final_checks.json b/evidence/final_checks.json new file mode 100644 index 00000000..b534ddf5 --- /dev/null +++ b/evidence/final_checks.json @@ -0,0 +1,86 @@ +{ + "before": [ + { + "name": "/lyakhonov-lab2-api-1", + "started_at": "2026-10-09T11:23:47.014525416Z", + "user": "appuser", + "image_id": "sha256:282821b02aeddc63acf7f264fe014cf4add9c798cbb687370d7ee21262567ff3", + "mounts": [] + }, + { + "name": "/lyakhonov-lab2-db-1", + "started_at": "2026-10-09T11:19:19.752878335Z", + "user": "", + "image_id": "sha256:1d04b9ba1d4996401f2552b51beda8187f175c0645c091e4781134fc9c9a3eef", + "mounts": [ + { + "name": "lyakhonov-lab2_postgres_data", + "destination": "/var/lib/postgresql/data" + } + ] + }, + { + "name": "/lyakhonov-lab2-redis-1", + "started_at": "2026-10-09T11:19:19.807227368Z", + "user": "", + "image_id": "sha256:c1e88455c85225310bbea54816e9c3f4b5295815e6dbf80c34d40afc6df28275", + "mounts": [ + { + "name": "lyakhonov-lab2_redis_data", + "destination": "/data" + } + ] + } + ], + "commands": [ + { + "command": "python scripts/check_contract.py", + "output": "PASS: offline skeleton structure, local refs and Python syntax; application NOT tested." + }, + { + "command": "python tests/smoke.py", + "output": "PASS: lab2 public API scenario; infrastructure and grading evidence remain separate." + }, + { + "command": "python student-tests/test_lab2.py", + "output": "PASS: strict validation, access, cursor binding, 100 messages / 10 clients, complete pagination" + }, + { + "command": "python tests/resilience.py --mode persistence --action-script scripts/restart.cmd", + "output": "Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.\nPASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence." + } + ], + "after": [ + { + "name": "/lyakhonov-lab2-api-1", + "started_at": "2026-10-09T11:25:00.737823332Z", + "user": "appuser", + "image_id": "sha256:282821b02aeddc63acf7f264fe014cf4add9c798cbb687370d7ee21262567ff3", + "mounts": [] + }, + { + "name": "/lyakhonov-lab2-db-1", + "started_at": "2026-10-09T11:25:00.409548723Z", + "user": "", + "image_id": "sha256:1d04b9ba1d4996401f2552b51beda8187f175c0645c091e4781134fc9c9a3eef", + "mounts": [ + { + "name": "lyakhonov-lab2_postgres_data", + "destination": "/var/lib/postgresql/data" + } + ] + }, + { + "name": "/lyakhonov-lab2-redis-1", + "started_at": "2026-10-09T11:25:00.307001994Z", + "user": "", + "image_id": "sha256:c1e88455c85225310bbea54816e9c3f4b5295815e6dbf80c34d40afc6df28275", + "mounts": [ + { + "name": "lyakhonov-lab2_redis_data", + "destination": "/data" + } + ] + } + ] +} diff --git a/scripts/wait_ready.py b/scripts/wait_ready.py new file mode 100644 index 00000000..35bd7e0d --- /dev/null +++ b/scripts/wait_ready.py @@ -0,0 +1,17 @@ +"""Дождаться HTTP readiness перед запуском проверок.""" +import argparse +import time +import urllib.request +parser=argparse.ArgumentParser() +parser.add_argument('--base-url',default='http://localhost:8080') +args=parser.parse_args() +for _ in range(120): + try: + with urllib.request.urlopen(args.base_url+'/health/ready',timeout=2) as response: + if response.status==200: + print('PASS: API ready') + break + except Exception: + time.sleep(0.5) +else: + raise SystemExit('API readiness timeout') diff --git a/src/routes/chats.py b/src/routes/chats.py index 4014fcf2..1324eca1 100644 --- a/src/routes/chats.py +++ b/src/routes/chats.py @@ -1,6 +1,6 @@ from uuid import UUID -from fastapi import APIRouter, Header, HTTPException, Request +from fastapi import APIRouter, Depends, HTTPException, Request from src.models import Chat, ChatPage, CreateChat from src.routes.common import get_request_id, make_error, require_user @@ -13,11 +13,10 @@ router = APIRouter() def create_chat( request: Request, body: CreateChat, - x_user_id: str | None = Header(None, alias="X-User-Id"), + x_user_id: str = Depends(require_user), ): """Создать чат. Создатель обязательно должен входить в member_ids.""" request_id = get_request_id(request) - x_user_id = require_user(request) try: chat = storage.create_chat(body.title, body.member_ids, x_user_id) @@ -37,13 +36,12 @@ def create_chat( @router.get("/api/v1/chats", response_model=ChatPage) def list_chats( request: Request, - x_user_id: str | None = Header(None, alias="X-User-Id"), + x_user_id: str = Depends(require_user), limit: int = 50, cursor: str | None = None, ): """Список чатов текущего пользователя с курсорной пагинацией.""" request_id = get_request_id(request) - x_user_id = require_user(request) if limit < 1 or limit > 100: raise HTTPException( @@ -65,11 +63,10 @@ def list_chats( def get_chat( request: Request, chat_id: UUID, - x_user_id: str | None = Header(None, alias="X-User-Id"), + x_user_id: str = Depends(require_user), ): """Получить чат по id. Доступен только участникам чата (чужой — 404).""" request_id = get_request_id(request) - x_user_id = require_user(request) chat_id_str = str(chat_id) chat = storage.get_chat(chat_id_str) diff --git a/src/routes/common.py b/src/routes/common.py index a671491d..628e51e6 100644 --- a/src/routes/common.py +++ b/src/routes/common.py @@ -17,7 +17,7 @@ def unauthorized(request, basic=False): raise HTTPException(401, detail=make_error('unauthorized', 'неверные учётные данные', get_request_id(request)).model_dump(), headers={'WWW-Authenticate': challenge}) -def require_user(request: Request, ignored=None): +def require_user(request: Request): authorization = request.headers.get('Authorization', '') parts = authorization.split() if len(parts) != 2 or parts[0].lower() != 'bearer': diff --git a/src/routes/messages.py b/src/routes/messages.py index c2b1adef..f28ce09f 100644 --- a/src/routes/messages.py +++ b/src/routes/messages.py @@ -1,6 +1,6 @@ from uuid import UUID -from fastapi import APIRouter, Header, HTTPException, Request +from fastapi import APIRouter, Depends, HTTPException, Request from src.models import CreateMessage, Message, MessagePage from src.routes.common import get_request_id, make_error, require_user @@ -14,11 +14,10 @@ def create_message( request: Request, chat_id: UUID, body: CreateMessage, - x_user_id: str | None = Header(None, alias="X-User-Id"), + x_user_id: str = Depends(require_user), ): """Отправить сообщение в чат. Отправитель определяется по X-User-Id.""" request_id = get_request_id(request) - x_user_id = require_user(request) chat_id_str = str(chat_id) chat = storage.get_chat(chat_id_str) @@ -42,13 +41,12 @@ def create_message( def list_messages( request: Request, chat_id: UUID, - x_user_id: str | None = Header(None, alias="X-User-Id"), + x_user_id: str = Depends(require_user), limit: int = 50, cursor: str | None = None, ): """История сообщений чата с курсорной пагинацией. Доступно только участникам.""" request_id = get_request_id(request) - x_user_id = require_user(request) chat_id_str = str(chat_id) chat = storage.get_chat(chat_id_str) diff --git a/student-tests/test_lab2.py b/student-tests/test_lab2.py index eeabd214..be0ec23f 100644 --- a/student-tests/test_lab2.py +++ b/student-tests/test_lab2.py @@ -17,6 +17,10 @@ def main(): c.call('POST',path,400,actor=alice,body={'text':'hello','sender_id':bob['id']}) c.call('POST',path,400,actor=alice,body={'text':' '}) c.call('GET','/api/v1/chats/not-a-uuid',400,actor=alice) + # Сначала идентификация, затем валидация и доступ к ресурсу. + c.call('GET','/api/v1/chats/not-a-uuid',401) + c.call('POST',path,401,body={'text':''}) + c.call('POST',path,400,actor=alice,raw=b'{',headers={'Content-Type':'application/json'}) c.call('POST',path,404,actor=eve,body={'text':'чужое'}) with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool: sent=list(pool.map(lambda i: c.message(alice,chat,'Параллельное '+str(i))['json'],range(100)))