Уточнил порядок аутентификации и подтвердил итоговые проверки

This commit is contained in:
2026-10-09 14:25:02 +03:00
parent 358ef4a046
commit 509161edca
6 changed files with 115 additions and 13 deletions
+86
View File
@@ -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"
}
]
}
]
}
+17
View File
@@ -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')
+4 -7
View File
@@ -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)
+1 -1
View File
@@ -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':
+3 -5
View File
@@ -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)
+4
View File
@@ -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)))