forked from mtusi2026/mtusi2026lab4
1300 lines
52 KiB
Python
1300 lines
52 KiB
Python
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import base64
|
||
import uuid
|
||
import httpx
|
||
|
||
import pytest
|
||
from httpx import AsyncClient
|
||
|
||
|
||
async def register_and_login(client: AsyncClient, prefix: str = "u") -> dict:
|
||
username = f"{prefix}_{uuid.uuid4().hex[:12]}"
|
||
password = f"P@ssword_{uuid.uuid4().hex[:8]}"
|
||
body = {
|
||
"username": username,
|
||
"display_name": f"User {prefix}",
|
||
"password": password,
|
||
}
|
||
u_res = await client.post("/api/v1/users", json=body)
|
||
assert u_res.status_code == 201, u_res.text
|
||
user = u_res.json()
|
||
|
||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||
s_res = await client.post(
|
||
"/api/v1/auth/sessions", headers={"Authorization": f"Basic {cred}"}
|
||
)
|
||
assert s_res.status_code == 201, s_res.text
|
||
session = s_res.json()
|
||
|
||
return {
|
||
"user": user,
|
||
"username": username,
|
||
"password": password,
|
||
"token": session["token"],
|
||
"headers": {"Authorization": f"Bearer {session['token']}"},
|
||
}
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_invalid_json_and_extra_fields(client: AsyncClient):
|
||
"""Проверка невалидного JSON, лишних полей, перевода строки и валидации курсора."""
|
||
# 1. Невалидный синтаксис JSON -> 400
|
||
res_malformed = await client.post(
|
||
"/api/v1/users",
|
||
content="not a valid json {",
|
||
headers={"Content-Type": "application/json"},
|
||
)
|
||
assert res_malformed.status_code == 400
|
||
err_malformed = res_malformed.json()
|
||
assert err_malformed["error"]["code"] == "invalid_request"
|
||
assert "request_id" in err_malformed["error"]
|
||
assert (
|
||
res_malformed.headers.get("X-Request-Id")
|
||
== err_malformed["error"]["request_id"]
|
||
)
|
||
|
||
# 2. Лишние поля (additionalProperties: false) -> 400
|
||
res_extra = await client.post(
|
||
"/api/v1/users",
|
||
json={
|
||
"username": f"u_{uuid.uuid4().hex[:8]}",
|
||
"display_name": "test_user",
|
||
"password": "ValidPassword123!",
|
||
"unexpected_field": "hacker_payload",
|
||
},
|
||
)
|
||
assert res_extra.status_code == 400
|
||
assert res_extra.json()["error"]["code"] == "invalid_request"
|
||
|
||
# 3. Запрет завершающего перевода строки в username ("abc\n") -> 400
|
||
res_newline = await client.post(
|
||
"/api/v1/users",
|
||
json={
|
||
"username": "abc\n",
|
||
"display_name": "test_newline",
|
||
"password": "ValidPassword123!",
|
||
},
|
||
)
|
||
assert res_newline.status_code == 400
|
||
assert res_newline.json()["error"]["code"] == "invalid_request"
|
||
|
||
# 4. Валидация курсора: не-dict JSON (W10= -> []) и пустой cursor= -> 400
|
||
actor = await register_and_login(client, "cur_val")
|
||
headers = actor["headers"]
|
||
|
||
# cursor=W10= (декодируется в list [], а не dict)
|
||
res_w10 = await client.get("/api/v1/chats?cursor=W10=", headers=headers)
|
||
assert res_w10.status_code == 400
|
||
assert res_w10.json()["error"]["code"] == "invalid_request"
|
||
|
||
# пустой cursor=
|
||
res_empty_cursor = await client.get("/api/v1/chats?cursor=", headers=headers)
|
||
assert res_empty_cursor.status_code == 400
|
||
assert res_empty_cursor.json()["error"]["code"] == "invalid_request"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_outsider_chat_access_is_404(client: AsyncClient):
|
||
"""Проверка того, что доступ к чужому чату возвращает строго 404 (а не 403)."""
|
||
alice = await register_and_login(client, "alice")
|
||
bob = await register_and_login(client, "bob")
|
||
eve = await register_and_login(client, "eve")
|
||
|
||
chat_res = await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={
|
||
"title": "Private Chat",
|
||
"member_ids": [alice["user"]["id"], bob["user"]["id"]],
|
||
},
|
||
)
|
||
assert chat_res.status_code == 201
|
||
chat_id = chat_res.json()["id"]
|
||
|
||
# Ева пытается получить чужой чат -> 404
|
||
res_get = await client.get(f"/api/v1/chats/{chat_id}", headers=eve["headers"])
|
||
assert res_get.status_code == 404
|
||
assert res_get.json()["error"]["code"] == "not_found"
|
||
|
||
# Ева пытается отправить сообщение в чужой чат -> 404
|
||
res_send = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**eve["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||
json={"text": "Шпионское сообщение"},
|
||
)
|
||
assert res_send.status_code == 404
|
||
assert res_send.json()["error"]["code"] == "not_found"
|
||
|
||
# Ева пытается прочитать сообщения чужого чата -> 404
|
||
res_list = await client.get(
|
||
f"/api/v1/chats/{chat_id}/messages", headers=eve["headers"]
|
||
)
|
||
assert res_list.status_code == 404
|
||
assert res_list.json()["error"]["code"] == "not_found"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_empty_and_whitespace_message(client: AsyncClient):
|
||
"""Проверка запрета отправки пустого текста или текста из одних пробелов (400)."""
|
||
alice = await register_and_login(client, "msg_user")
|
||
chat = (
|
||
await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Chat", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
).json()
|
||
|
||
# Пустая строка -> 400
|
||
res_empty = await client.post(
|
||
f"/api/v1/chats/{chat['id']}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||
json={"text": ""},
|
||
)
|
||
assert res_empty.status_code == 400
|
||
assert res_empty.json()["error"]["code"] == "invalid_request"
|
||
|
||
# Одни пробелы и переводы строк -> 400
|
||
res_whitespace = await client.post(
|
||
f"/api/v1/chats/{chat['id']}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||
json={"text": " \n\t "},
|
||
)
|
||
assert res_whitespace.status_code == 400
|
||
assert res_whitespace.json()["error"]["code"] == "invalid_request"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_duplicate_username_conflict(client: AsyncClient):
|
||
"""Проверка запрета дублирования username (409 conflict)."""
|
||
uname = f"uniq_{uuid.uuid4().hex[:10]}"
|
||
body = {
|
||
"username": uname,
|
||
"display_name": "Первый",
|
||
"password": "ValidPassword123!",
|
||
}
|
||
|
||
res1 = await client.post("/api/v1/users", json=body)
|
||
assert res1.status_code == 201
|
||
|
||
res2 = await client.post(
|
||
"/api/v1/users",
|
||
json={
|
||
"username": uname,
|
||
"display_name": "Второй с тем же ником",
|
||
"password": "AnotherPassword123!",
|
||
},
|
||
)
|
||
assert res2.status_code == 409
|
||
assert res2.json()["error"]["code"] == "conflict"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_wrong_password_and_bad_basic_auth(client: AsyncClient):
|
||
"""Проверка ошибки авторизации 401 и корректного заголовка WWW-Authenticate."""
|
||
alice = await register_and_login(client, "auth_test")
|
||
|
||
# Неверный пароль -> 401
|
||
bad_cred = base64.b64encode(f"{alice['username']}:WrongPassword123!".encode()).decode()
|
||
res_bad = await client.post(
|
||
"/api/v1/auth/sessions", headers={"Authorization": f"Basic {bad_cred}"}
|
||
)
|
||
assert res_bad.status_code == 401
|
||
assert res_bad.json()["error"]["code"] == "unauthorized"
|
||
assert "basic" in res_bad.headers.get("WWW-Authenticate", "").lower()
|
||
|
||
# Несуществующий юзер -> 401
|
||
ghost_cred = base64.b64encode(b"ghost_user_123:WrongPassword123!").decode()
|
||
res_ghost = await client.post(
|
||
"/api/v1/auth/sessions", headers={"Authorization": f"Basic {ghost_cred}"}
|
||
)
|
||
assert res_ghost.status_code == 401
|
||
assert "basic" in res_ghost.headers.get("WWW-Authenticate", "").lower()
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_logout_and_revocation(client: AsyncClient):
|
||
"""Проверка отзыва сессии (logout 204) и 401 при обращении с отозванным токеном."""
|
||
alice = await register_and_login(client, "logout_test")
|
||
|
||
# Проверяем, что токен работает
|
||
me_res = await client.get("/api/v1/users/me", headers=alice["headers"])
|
||
assert me_res.status_code == 200
|
||
|
||
# Делаем logout -> 204
|
||
logout_res = await client.delete(
|
||
"/api/v1/auth/sessions/current", headers=alice["headers"]
|
||
)
|
||
assert logout_res.status_code == 204
|
||
|
||
# Теперь тот же токен должен возвращать 401
|
||
me_after = await client.get("/api/v1/users/me", headers=alice["headers"])
|
||
assert me_after.status_code == 401
|
||
assert me_after.json()["error"]["code"] == "unauthorized"
|
||
assert "bearer" in me_after.headers.get("WWW-Authenticate", "").lower()
|
||
|
||
# Повторный logout с тем же отозванным токеном -> 401
|
||
logout_repeat = await client.delete(
|
||
"/api/v1/auth/sessions/current", headers=alice["headers"]
|
||
)
|
||
assert logout_repeat.status_code == 401
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_multi_page_cursor_pagination(client: AsyncClient):
|
||
"""Проверка обхода истории сообщений через keyset-курсор на нескольких страницах."""
|
||
alice = await register_and_login(client, "pager")
|
||
chat = (
|
||
await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Pagination Chat", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
).json()
|
||
|
||
# Отправляем 15 сообщений
|
||
sent_ids = []
|
||
for i in range(15):
|
||
msg = (
|
||
await client.post(
|
||
f"/api/v1/chats/{chat['id']}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||
json={"text": f"Сообщение {i:02d}"},
|
||
)
|
||
).json()
|
||
sent_ids.append(msg["id"])
|
||
|
||
# Читаем страницами по 4 сообщения
|
||
gathered_ids = []
|
||
cursor = None
|
||
pages_count = 0
|
||
|
||
while True:
|
||
url = f"/api/v1/chats/{chat['id']}/messages?limit=4"
|
||
if cursor:
|
||
url += f"&cursor={cursor}"
|
||
|
||
res = await client.get(url, headers=alice["headers"])
|
||
assert res.status_code == 200
|
||
data = res.json()
|
||
pages_count += 1
|
||
items = data["items"]
|
||
for item in items:
|
||
gathered_ids.append(item["id"])
|
||
|
||
cursor = data.get("next_cursor")
|
||
if not cursor:
|
||
break
|
||
|
||
# Должны быть ровно 15 сообщений в строго том же порядке, без дублей и пропусков
|
||
assert len(gathered_ids) == 15
|
||
assert gathered_ids == sent_ids
|
||
assert pages_count == 4
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_concurrency_race_condition(client: AsyncClient):
|
||
"""Проверка устойчивости к параллельным гонкам: 10 клиентов одновременно шлют 100 сообщений."""
|
||
# Создаём 10 пользователей
|
||
users = await asyncio.gather(
|
||
*(register_and_login(client, f"u{i}") for i in range(10))
|
||
)
|
||
all_user_ids = [u["user"]["id"] for u in users]
|
||
|
||
# Первый пользователь создаёт общий чат со всеми 10 участниками
|
||
chat = (
|
||
await client.post(
|
||
"/api/v1/chats",
|
||
headers=users[0]["headers"],
|
||
json={"title": "Massive Concurrent Chat", "member_ids": all_user_ids},
|
||
)
|
||
).json()
|
||
|
||
chat_id = chat["id"]
|
||
|
||
# Отправляем по 10 сообщений от каждого пользователя параллельно (всего 100)
|
||
async def sender(user_dict: dict, count: int):
|
||
for i in range(count):
|
||
await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**user_dict["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||
json={"text": f"Msg {i} from {user_dict['username']}"},
|
||
)
|
||
|
||
await asyncio.gather(*(sender(u, 10) for u in users))
|
||
|
||
# Считываем все сообщения из чата
|
||
all_msgs = []
|
||
cursor = None
|
||
while True:
|
||
url = f"/api/v1/chats/{chat_id}/messages?limit=50"
|
||
if cursor:
|
||
url += f"&cursor={cursor}"
|
||
res = await client.get(url, headers=users[0]["headers"])
|
||
assert res.status_code == 200
|
||
data = res.json()
|
||
all_msgs.extend(data["items"])
|
||
cursor = data.get("next_cursor")
|
||
if not cursor:
|
||
break
|
||
|
||
assert len(all_msgs) == 100
|
||
ids = [m["id"] for m in all_msgs]
|
||
# Все ID должны быть уникальными
|
||
assert len(ids) == len(set(ids))
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_password_whitespace_rejected(client: httpx.AsyncClient):
|
||
"""Пароль из одних пробелов должен строго отклоняться с 400 Invalid Request."""
|
||
u = f"space_user_{uuid.uuid4().hex[:6]}"
|
||
res = await client.post(
|
||
"/api/v1/users",
|
||
json={"username": u, "display_name": "Test User", "password": " " * 12},
|
||
)
|
||
assert res.status_code == 400
|
||
data = res.json()
|
||
assert data["error"]["code"] == "invalid_request"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_auth_sessions_with_body_rejected(client: httpx.AsyncClient):
|
||
"""POST /api/v1/auth/sessions с телом запроса должен отклоняться с 400 Invalid Request."""
|
||
u = f"body_user_{uuid.uuid4().hex[:6]}"
|
||
p = "StrongPassword123!"
|
||
await client.post(
|
||
"/api/v1/users",
|
||
json={"username": u, "display_name": "Body Test", "password": p},
|
||
)
|
||
cred = base64.b64encode(f"{u}:{p}".encode()).decode()
|
||
res = await client.post(
|
||
"/api/v1/auth/sessions",
|
||
headers={"Authorization": f"Basic {cred}"},
|
||
json={"extra": "forbidden"},
|
||
)
|
||
assert res.status_code == 400
|
||
data = res.json()
|
||
assert data["error"]["code"] == "invalid_request"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_unsupported_media_type_415(client: httpx.AsyncClient):
|
||
"""Запрос с неподдерживаемым Content-Type (text/plain) должен возвращать 415 Unsupported Media Type."""
|
||
res = await client.post(
|
||
"/api/v1/users",
|
||
content='{"username":"ct_test","display_name":"d","password":"Password123456!"}',
|
||
headers={"Content-Type": "text/plain"},
|
||
)
|
||
assert res.status_code == 415
|
||
data = res.json()
|
||
assert data["error"]["code"] == "unsupported_media_type"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_nul_byte_in_strings_handled(client: httpx.AsyncClient):
|
||
usr = await register_and_login(client, f"nul_msg_{uuid.uuid4().hex[:4]}")
|
||
chat = (await client.post("/api/v1/chats", headers=usr["headers"], json={"title": "NulChat", "member_ids": [usr["user"]["id"]]})).json()
|
||
test_text = "left\u0000right"
|
||
msg_res = await client.post(
|
||
f"/api/v1/chats/{chat['id']}/messages",
|
||
headers={**usr["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||
json={"text": test_text},
|
||
)
|
||
assert msg_res.status_code == 201
|
||
assert msg_res.json()["text"] == test_text
|
||
|
||
list_res = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=usr["headers"])
|
||
assert list_res.status_code == 200
|
||
assert any(m["text"] == test_text for m in list_res.json()["items"])
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_basic_auth_invalid_base64_returns_401(client: httpx.AsyncClient):
|
||
"""Authorization: Basic с битым base64 или не-ASCII символами возвращает 401, а не 500."""
|
||
res = await client.post(
|
||
"/api/v1/auth/sessions",
|
||
headers={"Authorization": b"Basic \xe9"},
|
||
)
|
||
assert res.status_code == 401
|
||
assert "Basic" in res.headers.get("www-authenticate", "")
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_cross_chat_cursor_rejected_400(client: httpx.AsyncClient):
|
||
"""Курсор от одного чата при попытке использовать в другом чате должен возвращать 400."""
|
||
u = await register_and_login(client, f"cc_{uuid.uuid4().hex[:4]}")
|
||
chat1 = (await client.post("/api/v1/chats", headers=u["headers"], json={"title": "C1", "member_ids": [u["user"]["id"]]})).json()
|
||
chat2 = (await client.post("/api/v1/chats", headers=u["headers"], json={"title": "C2", "member_ids": [u["user"]["id"]]})).json()
|
||
|
||
# Отправляем 2 сообщения в чат 1
|
||
await client.post(f"/api/v1/chats/{chat1['id']}/messages", headers={**u["headers"], "Idempotency-Key": uuid.uuid4().hex}, json={"text": "m1"})
|
||
await client.post(f"/api/v1/chats/{chat1['id']}/messages", headers={**u["headers"], "Idempotency-Key": uuid.uuid4().hex}, json={"text": "m2"})
|
||
|
||
# Получаем страницу с курсором из чата 1
|
||
p1 = (await client.get(f"/api/v1/chats/{chat1['id']}/messages?limit=1", headers=u["headers"])).json()
|
||
cursor1 = p1.get("next_cursor")
|
||
assert cursor1 is not None
|
||
|
||
# Пытаемся применить курсор чата 1 к чату 2 -> 400!
|
||
res = await client.get(f"/api/v1/chats/{chat2['id']}/messages?cursor={cursor1}", headers=u["headers"])
|
||
assert res.status_code == 400
|
||
assert res.json()["error"]["code"] == "invalid_request"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_utf8_password_support(client: httpx.AsyncClient):
|
||
"""Пароли с символами UTF-8 и emoji корректно регистрируются и аутентифицируются."""
|
||
u = f"utf_{uuid.uuid4().hex[:6]}"
|
||
p = "СложныйПароль123!🔒"
|
||
res1 = await client.post(
|
||
"/api/v1/users",
|
||
json={"username": u, "display_name": "UTF User", "password": p},
|
||
)
|
||
assert res1.status_code == 201
|
||
|
||
cred = base64.b64encode(f"{u}:{p}".encode("utf-8")).decode("utf-8")
|
||
res2 = await client.post(
|
||
"/api/v1/auth/sessions",
|
||
headers={"Authorization": f"Basic {cred}"},
|
||
)
|
||
assert res2.status_code == 201
|
||
assert "token" in res2.json()
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_health_readiness_and_liveness(client: httpx.AsyncClient):
|
||
"""Проверка доступности /health/live и готовности хранилищ /health/ready."""
|
||
r_live = await client.get("/health/live")
|
||
assert r_live.status_code == 200
|
||
assert r_live.json()["status"] == "ok"
|
||
|
||
r_ready = await client.get("/health/ready")
|
||
assert r_ready.status_code == 200
|
||
assert r_ready.json()["status"] == "ok"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_instance_id_header_present(client: httpx.AsyncClient):
|
||
"""Каждый ответ обязан содержать непустой заголовок X-Instance-Id."""
|
||
res = await client.get("/health/live")
|
||
assert res.status_code == 200
|
||
assert "x-instance-id" in res.headers
|
||
assert len(res.headers["x-instance-id"]) > 0
|
||
|
||
res_err = await client.get("/api/v1/users/me")
|
||
assert res_err.status_code == 401
|
||
assert "x-instance-id" in res_err.headers
|
||
assert len(res_err.headers["x-instance-id"]) > 0
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_idempotency_key_validation(client: httpx.AsyncClient):
|
||
"""POST /messages без Idempotency-Key или с некорректным форматом возвращает 400."""
|
||
alice = await register_and_login(client, f"idem_{uuid.uuid4().hex[:6]}")
|
||
chat = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "IdemChat", "member_ids": [alice["user"]["id"]]})).json()
|
||
chat_id = chat["id"]
|
||
|
||
# Без заголовка
|
||
res1 = await client.post(f"/api/v1/chats/{chat_id}/messages", headers=alice["headers"], json={"text": "Тест"})
|
||
assert res1.status_code == 400
|
||
assert res1.json()["error"]["code"] == "invalid_request"
|
||
|
||
# С некорректным форматом
|
||
res2 = await client.post(f"/api/v1/chats/{chat_id}/messages", headers={**alice["headers"], "Idempotency-Key": "invalid key with spaces"}, json={"text": "Тест"})
|
||
assert res2.status_code == 400
|
||
assert res2.json()["error"]["code"] == "invalid_request"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_idempotency_replay_and_conflict(client: httpx.AsyncClient):
|
||
"""Повтор с тем же телом возвращает исходный 201; с другим телом возвращает 409."""
|
||
alice = await register_and_login(client, f"idem2_{uuid.uuid4().hex[:6]}")
|
||
chat = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "IdemChat2", "member_ids": [alice["user"]["id"]]})).json()
|
||
chat_id = chat["id"]
|
||
key = uuid.uuid4().hex
|
||
|
||
# Первый запрос -> 201
|
||
res1 = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": key},
|
||
json={"text": "Первое сообщение"},
|
||
)
|
||
assert res1.status_code == 201
|
||
msg1 = res1.json()
|
||
|
||
# Повтор с тем же телом -> 201 и то же сообщение
|
||
res2 = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": key},
|
||
json={"text": "Первое сообщение"},
|
||
)
|
||
assert res2.status_code == 201
|
||
assert res2.json() == msg1
|
||
|
||
# Повтор с тем же ключом, но другим телом -> 409 Conflict
|
||
res3 = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": key},
|
||
json={"text": "Другое сообщение с тем же ключом"},
|
||
)
|
||
assert res3.status_code == 409
|
||
assert res3.json()["error"]["code"] == "conflict"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_idempotency_acl_check_on_replay(client: httpx.AsyncClient):
|
||
"""
|
||
Проверка ACL перед возвратом сохранённого результата идемпотентности.
|
||
Если пользователь удалён из участников чата, повторный POST с тем же Idempotency-Key
|
||
и тем же телом обязан вернуть 404 (а не 201).
|
||
"""
|
||
import subprocess
|
||
|
||
alice = await register_and_login(client, f"acl_{uuid.uuid4().hex[:6]}")
|
||
chat = (
|
||
await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "ACL Test Chat", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
).json()
|
||
chat_id = chat["id"]
|
||
user_id = alice["user"]["id"]
|
||
key = f"acl_key_{uuid.uuid4().hex[:12]}"
|
||
|
||
# 1. Отправляем сообщение первый раз -> 201
|
||
res1 = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": key},
|
||
json={"text": "Тест проверки ACL"},
|
||
)
|
||
assert res1.status_code == 201
|
||
|
||
# 2. Удаляем членство отправителя напрямую в БД (изолированная инъекция проверки ACL)
|
||
cmd = [
|
||
"docker",
|
||
"compose",
|
||
"exec",
|
||
"-T",
|
||
"postgres",
|
||
"psql",
|
||
"-U",
|
||
"postgres",
|
||
"-d",
|
||
"messenger",
|
||
"-c",
|
||
f"DELETE FROM chat_members WHERE chat_id = '{chat_id}' AND user_id = '{user_id}';",
|
||
]
|
||
sub_res = subprocess.run(cmd, capture_output=True, text=True)
|
||
assert sub_res.returncode == 0, f"Ошибка удаления членства: {sub_res.stderr}"
|
||
|
||
# 3. GET истории уже обязан возвращать 404
|
||
res_get = await client.get(f"/api/v1/chats/{chat_id}/messages", headers=alice["headers"])
|
||
assert res_get.status_code == 404
|
||
|
||
# 4. Повтор POST с тем же телом и тем же ключом ОБЯЗАН вернуть 404 (ACL проверяется до возврата из idempotency_keys)
|
||
res_repeat = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": key},
|
||
json={"text": "Тест проверки ACL"},
|
||
)
|
||
assert res_repeat.status_code == 404, f"Ожидался 404, получен {res_repeat.status_code}: {res_repeat.text}"
|
||
assert res_repeat.json()["error"]["code"] == "not_found"
|
||
|
||
# 5. Повтор POST с тем же ключом и ДРУГИМ телом: ACL проверяется до сравнения тела -> обязан вернуть 404 (а не 409)
|
||
res_repeat_diff = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": key},
|
||
json={"text": "Другой текст сообщения"},
|
||
)
|
||
assert res_repeat_diff.status_code == 404, f"Ожидался 404, получен {res_repeat_diff.status_code}: {res_repeat_diff.text}"
|
||
assert res_repeat_diff.json()["error"]["code"] == "not_found"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_invalid_cursor_date_returns_400(client: httpx.AsyncClient):
|
||
"""
|
||
Некорректная дата курсора (например, 13-й месяц 2026-13-01T00:00:00.000000Z)
|
||
обязана возвращать 400 invalid_request (а не 500 internal_error).
|
||
"""
|
||
from app.storage import encode_cursor
|
||
|
||
alice = await register_and_login(client, f"bad_cur_{uuid.uuid4().hex[:6]}")
|
||
chat = (
|
||
await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "CurChat", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
).json()
|
||
chat_id = chat["id"]
|
||
|
||
# 1. Курсор сообщений с невалидной датой (месяц 13)
|
||
bad_cur_msg = encode_cursor(
|
||
{
|
||
"type": "messages",
|
||
"chat_id": chat_id,
|
||
"created_at": "2026-13-01T00:00:00.000000Z",
|
||
"id": str(uuid.uuid4()),
|
||
}
|
||
)
|
||
res_m = await client.get(
|
||
f"/api/v1/chats/{chat_id}/messages?cursor={bad_cur_msg}",
|
||
headers=alice["headers"],
|
||
)
|
||
assert res_m.status_code == 400
|
||
assert res_m.json()["error"]["code"] == "invalid_request"
|
||
|
||
# 2. Невалидная строка формата m|chat_id|... в base64
|
||
raw_str = f"m|{chat_id}|2026-13-01T00:00:00.000000Z|"
|
||
raw_cur = base64.urlsafe_b64encode(raw_str.encode()).decode()
|
||
res_raw = await client.get(
|
||
f"/api/v1/chats/{chat_id}/messages?cursor={raw_cur}",
|
||
headers=alice["headers"],
|
||
)
|
||
assert res_raw.status_code == 400
|
||
assert res_raw.json()["error"]["code"] == "invalid_request"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_strict_types_and_json_parsing(client: httpx.AsyncClient):
|
||
"""
|
||
Запрет преобразования неверных типов ({"text": 123} -> 400)
|
||
и требование полного разбора JSON ({"text":"x"}garbage -> 400).
|
||
"""
|
||
alice = await register_and_login(client, f"strict_{uuid.uuid4().hex[:6]}")
|
||
chat = (
|
||
await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "StrictChat", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
).json()
|
||
chat_id = chat["id"]
|
||
|
||
# 1. {"text": 123} вместо строки -> 400
|
||
res_num = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex, "Content-Type": "application/json"},
|
||
content='{"text": 123}',
|
||
)
|
||
assert res_num.status_code == 400
|
||
assert res_num.json()["error"]["code"] == "invalid_request"
|
||
|
||
# 2. {"text": "x"}garbage -> 400
|
||
res_garbage = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex, "Content-Type": "application/json"},
|
||
content='{"text": "x"}garbage',
|
||
)
|
||
assert res_garbage.status_code == 400
|
||
assert res_garbage.json()["error"]["code"] == "invalid_request"
|
||
|
||
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_chat_creation_with_unknown_participant_is_400(client: httpx.AsyncClient):
|
||
"""Неизвестный участник при создании чата обязан возвращать 400 (не 404)."""
|
||
alice = await register_and_login(client, f"unk_{uuid.uuid4().hex[:6]}")
|
||
non_existent_uuid = str(uuid.uuid4())
|
||
|
||
res = await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Chat With Ghost", "member_ids": [alice["user"]["id"], non_existent_uuid]},
|
||
)
|
||
assert res.status_code == 400
|
||
assert res.json()["error"]["code"] == "invalid_request"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_password_with_colons_and_utf8(client: httpx.AsyncClient):
|
||
"""Пароль с двоеточиями и UTF-8 символами работает при регистрации и входе."""
|
||
username = f"col_{uuid.uuid4().hex[:8]}"
|
||
password = "Пример:пароля-12345:секрет:🔒"
|
||
|
||
res_reg = await client.post(
|
||
"/api/v1/users",
|
||
json={"username": username, "display_name": "Colon User", "password": password},
|
||
)
|
||
assert res_reg.status_code == 201
|
||
|
||
cred = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("utf-8")
|
||
res_login = await client.post(
|
||
"/api/v1/auth/sessions",
|
||
headers={"Authorization": f"Basic {cred}"},
|
||
)
|
||
assert res_login.status_code == 201
|
||
assert "token" in res_login.json()
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_keyset_pagination_returns_next_cursor(client: httpx.AsyncClient):
|
||
"""
|
||
При наличии записей за пределами limit возвращается next_cursor.
|
||
Повторный запрос с cursor возвращает следующие элементы.
|
||
"""
|
||
alice = await register_and_login(client, f"page_{uuid.uuid4().hex[:6]}")
|
||
c1 = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "Chat1", "member_ids": [alice["user"]["id"]]})).json()
|
||
c2 = (await client.post("/api/v1/chats", headers=alice["headers"], json={"title": "Chat2", "member_ids": [alice["user"]["id"]]})).json()
|
||
|
||
# Запрос с limit=1 обязан вернуть первый чат и НЕПУСТОЙ next_cursor
|
||
res_p1 = await client.get("/api/v1/chats?limit=1", headers=alice["headers"])
|
||
assert res_p1.status_code == 200
|
||
data_p1 = res_p1.json()
|
||
assert len(data_p1["items"]) == 1
|
||
cursor = data_p1["next_cursor"]
|
||
assert cursor is not None and len(cursor) > 0
|
||
|
||
# Запрос со вторым курсором обязан вернуть второй чат
|
||
res_p2 = await client.get(f"/api/v1/chats?limit=1&cursor={cursor}", headers=alice["headers"])
|
||
assert res_p2.status_code == 200
|
||
data_p2 = res_p2.json()
|
||
assert len(data_p2["items"]) == 1
|
||
assert data_p2["items"][0]["id"] != data_p1["items"][0]["id"]
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_attachment_upload_and_download_flow(client: httpx.AsyncClient):
|
||
"""Проверка полного цикла загрузки и скачивания PNG и JPEG вложений."""
|
||
import hashlib
|
||
import io
|
||
from PIL import Image
|
||
|
||
alice = await register_and_login(client, "att_a")
|
||
bob = await register_and_login(client, "att_b")
|
||
|
||
chat_res = await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Attach Chat", "member_ids": [alice["user"]["id"], bob["user"]["id"]]},
|
||
)
|
||
assert chat_res.status_code == 201
|
||
chat_id = chat_res.json()["id"]
|
||
|
||
# 1. Загрузка PNG
|
||
with open("tests/fixtures/sample.png", "rb") as f:
|
||
png_data = f.read()
|
||
|
||
png_sha = hashlib.sha256(png_data).hexdigest()
|
||
up_res = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=sample.png",
|
||
headers={**alice["headers"], "Content-Type": "image/png"},
|
||
content=png_data,
|
||
)
|
||
assert up_res.status_code == 201, up_res.text
|
||
att_png = up_res.json()
|
||
assert att_png["chat_id"] == chat_id
|
||
assert att_png["owner_id"] == alice["user"]["id"]
|
||
assert att_png["filename"] == "sample.png"
|
||
assert att_png["content_type"] == "image/png"
|
||
assert att_png["size_bytes"] == len(png_data)
|
||
assert att_png["sha256"] == png_sha
|
||
assert att_png["status"] == "ready"
|
||
assert att_png["variants"] == []
|
||
assert att_png["error_code"] is None
|
||
|
||
# 2. Получение метаданных Бобом
|
||
meta_res = await client.get(
|
||
f"/api/v1/attachments/{att_png['id']}",
|
||
headers=bob["headers"],
|
||
)
|
||
assert meta_res.status_code == 200
|
||
assert meta_res.json() == att_png
|
||
|
||
# 3. Скачивание контента Бобом
|
||
down_res = await client.get(
|
||
f"/api/v1/attachments/{att_png['id']}/content",
|
||
headers=bob["headers"],
|
||
)
|
||
assert down_res.status_code == 200
|
||
assert down_res.headers.get("content-type") == "image/png"
|
||
assert down_res.content == png_data
|
||
|
||
# 4. Загрузка и скачивание JPEG
|
||
jpeg_img = Image.new("RGB", (64, 64), color=(255, 128, 0))
|
||
jpeg_buf = io.BytesIO()
|
||
jpeg_img.save(jpeg_buf, format="JPEG")
|
||
jpeg_data = jpeg_buf.getvalue()
|
||
|
||
up_jpeg = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=orange.jpg",
|
||
headers={**alice["headers"], "Content-Type": "image/jpeg"},
|
||
content=jpeg_data,
|
||
)
|
||
assert up_jpeg.status_code == 201
|
||
att_jpeg = up_jpeg.json()
|
||
assert att_jpeg["content_type"] == "image/jpeg"
|
||
assert att_jpeg["size_bytes"] == len(jpeg_data)
|
||
|
||
down_jpeg = await client.get(
|
||
f"/api/v1/attachments/{att_jpeg['id']}/content",
|
||
headers=bob["headers"],
|
||
)
|
||
assert down_jpeg.status_code == 200
|
||
assert down_jpeg.headers.get("content-type") == "image/jpeg"
|
||
assert down_jpeg.content == jpeg_data
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_attachment_unsupported_media_type_and_magic_bytes(client: httpx.AsyncClient):
|
||
"""Проверка отклонения невалидных MIME-типов и поврежденных сигнатур (415)."""
|
||
alice = await register_and_login(client, "mime_a")
|
||
chat_res = await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Mime Chat", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
chat_id = chat_res.json()["id"]
|
||
|
||
# 1. Неподдерживаемый Content-Type: text/plain -> 415
|
||
res1 = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=test.txt",
|
||
headers={**alice["headers"], "Content-Type": "text/plain"},
|
||
content=b"plain text",
|
||
)
|
||
assert res1.status_code == 415
|
||
assert res1.json()["error"]["code"] == "unsupported_media_type"
|
||
|
||
# 2. Неподдерживаемый Content-Type: image/gif -> 415
|
||
res2 = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=anim.gif",
|
||
headers={**alice["headers"], "Content-Type": "image/gif"},
|
||
content=b"GIF89a...",
|
||
)
|
||
assert res2.status_code == 415
|
||
assert res2.json()["error"]["code"] == "unsupported_media_type"
|
||
|
||
# 3. Content-Type image/png, но поврежденные магические байты -> 415
|
||
res3 = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=fake.png",
|
||
headers={**alice["headers"], "Content-Type": "image/png"},
|
||
content=b"NOT_A_PNG_HEADER_HERE",
|
||
)
|
||
assert res3.status_code == 415
|
||
assert res3.json()["error"]["code"] == "unsupported_media_type"
|
||
|
||
# 4. Content-Type image/jpeg, но поврежденные магические байты -> 415
|
||
res4 = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=fake.jpg",
|
||
headers={**alice["headers"], "Content-Type": "image/jpeg"},
|
||
content=b"NOT_A_JPEG_HEADER_HERE",
|
||
)
|
||
assert res4.status_code == 415
|
||
assert res4.json()["error"]["code"] == "unsupported_media_type"
|
||
|
||
# 5. Поврежденный JPEG без пиксельных данных (18 байт) -> 415
|
||
bad_jpeg_18 = bytes.fromhex("ffd8ffc00008080001000101ffda0002ffd9")
|
||
res5 = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=bad18.jpg",
|
||
headers={**alice["headers"], "Content-Type": "image/jpeg"},
|
||
content=bad_jpeg_18,
|
||
)
|
||
assert res5.status_code == 415
|
||
assert res5.json()["error"]["code"] == "unsupported_media_type"
|
||
|
||
# 6. Обрезанный PNG без пиксельных данных (33 байта) -> 415
|
||
bad_png_33 = bytes.fromhex("89504e470d0a1a0a0000000d4948445200000001000000010802000000907753de")
|
||
res6 = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=bad33.png",
|
||
headers={**alice["headers"], "Content-Type": "image/png"},
|
||
content=bad_png_33,
|
||
)
|
||
assert res6.status_code == 415
|
||
assert res6.json()["error"]["code"] == "unsupported_media_type"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_attachment_filename_validation(client: httpx.AsyncClient):
|
||
"""Проверка валидации имени файла (path traversal, длина, спецсимволы -> 400)."""
|
||
alice = await register_and_login(client, "fname_a")
|
||
chat_res = await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Filename Chat", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
chat_id = chat_res.json()["id"]
|
||
|
||
with open("tests/fixtures/sample.png", "rb") as f:
|
||
valid_png = f.read()
|
||
|
||
headers = {**alice["headers"], "Content-Type": "image/png"}
|
||
|
||
# 1. Path traversal со слешем /
|
||
res_slash = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=../../etc/passwd",
|
||
headers=headers,
|
||
content=valid_png,
|
||
)
|
||
assert res_slash.status_code == 400
|
||
assert res_slash.json()["error"]["code"] == "invalid_request"
|
||
|
||
# 2. Path traversal с обратным слешем \
|
||
res_bslash = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=..\\boot.ini",
|
||
headers=headers,
|
||
content=valid_png,
|
||
)
|
||
assert res_bslash.status_code == 400
|
||
assert res_bslash.json()["error"]["code"] == "invalid_request"
|
||
|
||
# 3. Символ перевода строки \n
|
||
res_nl = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=file%0Aname.png",
|
||
headers=headers,
|
||
content=valid_png,
|
||
)
|
||
assert res_nl.status_code == 400
|
||
assert res_nl.json()["error"]["code"] == "invalid_request"
|
||
|
||
# 4. Превышение 255 символов
|
||
long_name = "a" * 256 + ".png"
|
||
res_long = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename={long_name}",
|
||
headers=headers,
|
||
content=valid_png,
|
||
)
|
||
assert res_long.status_code == 400
|
||
assert res_long.json()["error"]["code"] == "invalid_request"
|
||
|
||
# 5. Пустое имя файла
|
||
res_empty = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=",
|
||
headers=headers,
|
||
content=valid_png,
|
||
)
|
||
assert res_empty.status_code == 400
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_attachment_payload_too_large_and_pixel_bomb(client: httpx.AsyncClient):
|
||
"""Проверка лимита размера файла (>10 MiB) и бомбы декомпрессии (>40M px) -> 413."""
|
||
import io
|
||
from PIL import Image
|
||
|
||
alice = await register_and_login(client, "large_a")
|
||
chat_res = await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Large Chat", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
chat_id = chat_res.json()["id"]
|
||
|
||
# 1. Размер файла более 10 MiB (10 * 1024 * 1024 + 10 байт) -> 413
|
||
oversize_bytes = b"\x89PNG\r\n\x1a\n" + b"\x00" * (10 * 1024 * 1024 + 10)
|
||
res_oversize = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=huge.png",
|
||
headers={**alice["headers"], "Content-Type": "image/png"},
|
||
content=oversize_bytes,
|
||
)
|
||
assert res_oversize.status_code == 413
|
||
assert res_oversize.json()["error"]["code"] == "payload_too_large"
|
||
|
||
# 2. Бомба декомпрессии (10000x5000 = 50 млн пикселей > 40 млн пикселей) -> 413
|
||
bomb_img = Image.new("L", (10000, 5000), color=0)
|
||
bomb_buf = io.BytesIO()
|
||
bomb_img.save(bomb_buf, format="PNG")
|
||
bomb_bytes = bomb_buf.getvalue()
|
||
|
||
res_bomb = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=pixel_bomb.png",
|
||
headers={**alice["headers"], "Content-Type": "image/png"},
|
||
content=bomb_bytes,
|
||
)
|
||
assert res_bomb.status_code == 413
|
||
assert res_bomb.json()["error"]["code"] == "payload_too_large"
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_attachment_acl_and_isolation(client: httpx.AsyncClient):
|
||
"""Проверка строгой изоляции: посторонний пользователь получает 404 на все операции."""
|
||
alice = await register_and_login(client, "acl_a")
|
||
eve = await register_and_login(client, "acl_eve")
|
||
|
||
chat_res = await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Private Chat", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
chat_id = chat_res.json()["id"]
|
||
|
||
with open("tests/fixtures/sample.png", "rb") as f:
|
||
png_data = f.read()
|
||
|
||
# 1. Посторонний пытается загрузить вложение в чужой чат -> 404
|
||
res_eve_up = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=sample.png",
|
||
headers={**eve["headers"], "Content-Type": "image/png"},
|
||
content=png_data,
|
||
)
|
||
assert res_eve_up.status_code == 404
|
||
assert res_eve_up.json()["error"]["code"] == "not_found"
|
||
|
||
# Алиса загружает файл
|
||
res_alice_up = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=sample.png",
|
||
headers={**alice["headers"], "Content-Type": "image/png"},
|
||
content=png_data,
|
||
)
|
||
assert res_alice_up.status_code == 201
|
||
att_id = res_alice_up.json()["id"]
|
||
|
||
# 2. Посторонний пытается запросить метаданные -> 404
|
||
res_eve_meta = await client.get(
|
||
f"/api/v1/attachments/{att_id}",
|
||
headers=eve["headers"],
|
||
)
|
||
assert res_eve_meta.status_code == 404
|
||
|
||
# 3. Посторонний пытается скачать контент -> 404
|
||
res_eve_down = await client.get(
|
||
f"/api/v1/attachments/{att_id}/content",
|
||
headers=eve["headers"],
|
||
)
|
||
assert res_eve_down.status_code == 404
|
||
|
||
# 4. Несуществующий attachment ID -> 404
|
||
random_uuid = str(uuid.uuid4())
|
||
res_not_found = await client.get(
|
||
f"/api/v1/attachments/{random_uuid}",
|
||
headers=alice["headers"],
|
||
)
|
||
assert res_not_found.status_code == 404
|
||
|
||
# 5. Невалидный UUID -> 400
|
||
res_bad_uuid = await client.get(
|
||
"/api/v1/attachments/not-a-uuid",
|
||
headers=alice["headers"],
|
||
)
|
||
assert res_bad_uuid.status_code == 400
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_message_linking_attachments(client: httpx.AsyncClient):
|
||
"""Проверка связывания сообщений и вложений: пустой текст с вложением, чужие вложения, лимит 10."""
|
||
alice = await register_and_login(client, "msg_att_a")
|
||
bob = await register_and_login(client, "msg_att_b")
|
||
|
||
chat_res = await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Msg Attach Chat", "member_ids": [alice["user"]["id"], bob["user"]["id"]]},
|
||
)
|
||
chat_id = chat_res.json()["id"]
|
||
|
||
chat2_res = await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Chat 2", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
chat2_id = chat2_res.json()["id"]
|
||
|
||
with open("tests/fixtures/sample.png", "rb") as f:
|
||
png_data = f.read()
|
||
|
||
# Загружаем вложение в chat 1
|
||
up1 = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=sample.png",
|
||
headers={**alice["headers"], "Content-Type": "image/png"},
|
||
content=png_data,
|
||
)
|
||
att1_id = up1.json()["id"]
|
||
|
||
# Загружаем вложение в chat 2
|
||
up2 = await client.post(
|
||
f"/api/v1/chats/{chat2_id}/attachments?filename=chat2.png",
|
||
headers={**alice["headers"], "Content-Type": "image/png"},
|
||
content=png_data,
|
||
)
|
||
att2_id = up2.json()["id"]
|
||
|
||
# 1. Сообщение с пустым текстом, но с вложением -> 201
|
||
msg1_res = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||
json={"text": "", "attachment_ids": [att1_id]},
|
||
)
|
||
assert msg1_res.status_code == 201, msg1_res.text
|
||
msg1 = msg1_res.json()
|
||
assert msg1["text"] == ""
|
||
assert msg1["attachment_ids"] == [att1_id]
|
||
|
||
# 2. Сообщение с пустым текстом И без вложений -> 400
|
||
msg2_res = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||
json={"text": "", "attachment_ids": []},
|
||
)
|
||
assert msg2_res.status_code == 400
|
||
|
||
# 3. Прикрепление вложения из другого чата -> 404
|
||
msg3_res = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||
json={"text": "Hello", "attachment_ids": [att2_id]},
|
||
)
|
||
assert msg3_res.status_code == 404
|
||
|
||
# 4. Прикрепление несуществующего вложения -> 404
|
||
fake_uuid = str(uuid.uuid4())
|
||
msg4_res = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||
json={"text": "Hello", "attachment_ids": [fake_uuid]},
|
||
)
|
||
assert msg4_res.status_code == 404
|
||
|
||
# 5. Более 10 вложений -> 400
|
||
eleven_uuids = [str(uuid.uuid4()) for _ in range(11)]
|
||
msg5_res = await client.post(
|
||
f"/api/v1/chats/{chat_id}/messages",
|
||
headers={**alice["headers"], "Idempotency-Key": uuid.uuid4().hex},
|
||
json={"text": "Hello", "attachment_ids": eleven_uuids},
|
||
)
|
||
assert msg5_res.status_code == 400
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_attachment_orphan_compensation(client: httpx.AsyncClient):
|
||
"""
|
||
Проверка компенсации сиротских объектов S3 при сбое БД (критерий оценки 4):
|
||
1. Через docker compose exec в PostgreSQL создаём триггер, вызывающий сбой при записи файла 'orphan_sim_fail.png'.
|
||
2. Выполняем POST вложения 'orphan_sim_fail.png'.
|
||
S3 PUT проходит успешно, но при вставке в PostgreSQL возникает ошибка.
|
||
Сервер перехватывает ошибку, вызывает s3_client.delete_object и возвращает 500.
|
||
3. Проверяем, что сиротский объект удалён из S3 (через проверку через api-1/boto3).
|
||
4. Удаляем триггер из PostgreSQL.
|
||
"""
|
||
import subprocess
|
||
alice = await register_and_login(client, "orph_a")
|
||
chat_res = await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Orphan Chat", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
chat_id = chat_res.json()["id"]
|
||
|
||
setup_sql = """
|
||
CREATE OR REPLACE FUNCTION trg_sim_fail() RETURNS TRIGGER AS $$
|
||
BEGIN
|
||
IF NEW.filename = 'orphan_sim_fail.png' THEN
|
||
RAISE EXCEPTION 'Simulated DB failure for orphan compensation test';
|
||
END IF;
|
||
RETURN NEW;
|
||
END;
|
||
$$ LANGUAGE plpgsql;
|
||
|
||
DROP TRIGGER IF EXISTS check_orphan_sim ON attachments;
|
||
CREATE TRIGGER check_orphan_sim BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION trg_sim_fail();
|
||
"""
|
||
cmd = ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "postgres", "-d", "messenger", "-c", setup_sql]
|
||
sub_res = subprocess.run(cmd, capture_output=True, text=True)
|
||
assert sub_res.returncode == 0, f"Ошибка создания триггера: {sub_res.stderr}"
|
||
|
||
try:
|
||
with open("tests/fixtures/sample.png", "rb") as f:
|
||
png_data = f.read()
|
||
|
||
res = await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=orphan_sim_fail.png",
|
||
headers={**alice["headers"], "Content-Type": "image/png"},
|
||
content=png_data,
|
||
)
|
||
assert res.status_code in (500, 503)
|
||
|
||
check_py = f"""
|
||
import boto3
|
||
s3 = boto3.client('s3', endpoint_url='http://minio:9000', aws_access_key_id='minioadmin', aws_secret_access_key='minioadmin')
|
||
res = s3.list_objects_v2(Bucket='messenger-attachments', Prefix='chats/{chat_id}/')
|
||
keys = [o['Key'] for o in res.get('Contents', [])]
|
||
found = any('orphan_sim_fail.png' in k for k in keys)
|
||
print('FOUND' if found else 'NOT_FOUND')
|
||
"""
|
||
cmd_s3 = ["docker", "compose", "exec", "-T", "api-1", "python", "-c", check_py]
|
||
s3_res = subprocess.run(cmd_s3, capture_output=True, text=True)
|
||
assert s3_res.returncode == 0
|
||
assert "NOT_FOUND" in s3_res.stdout, f"Сиротский объект остался в S3! Вывод: {s3_res.stdout}"
|
||
finally:
|
||
cleanup_sql = """
|
||
DROP TRIGGER IF EXISTS check_orphan_sim ON attachments;
|
||
DROP FUNCTION IF EXISTS trg_sim_fail();
|
||
"""
|
||
cmd_clean = ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "postgres", "-d", "messenger", "-c", cleanup_sql]
|
||
subprocess.run(cmd_clean, capture_output=True, text=True)
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_private_bucket_outside_api(client: httpx.AsyncClient):
|
||
"""
|
||
Проверка закрытости S3 бакета вне API (критерий оценки 4):
|
||
1. Порты MinIO (9000/9001) не проброшены на хост наружу -> прямое подключение отклоняется.
|
||
2. Балансировщик Nginx маршрутизирует только /api/ и /health/, запрос к S3 напрямую через LB возвращает 404.
|
||
3. Неаутентифицированный запрос на скачивание вложения возвращает 401 Unauthorized.
|
||
"""
|
||
direct_conn_failed = False
|
||
try:
|
||
async with httpx.AsyncClient() as raw_client:
|
||
await raw_client.get("http://localhost:9000", timeout=1.0)
|
||
except httpx.ConnectError:
|
||
direct_conn_failed = True
|
||
assert direct_conn_failed, "Порт 9000 MinIO не должен быть доступен с хоста!"
|
||
|
||
res_lb_s3 = await client.get("/messenger-attachments/")
|
||
assert res_lb_s3.status_code == 404
|
||
|
||
random_id = str(uuid.uuid4())
|
||
res_anon = await client.get(f"/api/v1/attachments/{random_id}/content")
|
||
assert res_anon.status_code == 401
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_concurrent_uploads_memory_limit(client: httpx.AsyncClient):
|
||
"""
|
||
Проверка конкурентной загрузки ≥10 файлов с контролем потребления RAM (критерий оценки 4):
|
||
1. Создаем пользователя и чат.
|
||
2. Запускаем параллельную загрузку 10 изображений через asyncio.gather.
|
||
3. Измеряем память контейнеров API через docker stats.
|
||
4. Все 10 загрузок завершаются успехом (201 Created), память остаётся в стабильных границах.
|
||
"""
|
||
import subprocess
|
||
alice = await register_and_login(client, "conc_a")
|
||
chat_res = await client.post(
|
||
"/api/v1/chats",
|
||
headers=alice["headers"],
|
||
json={"title": "Concurrent Uploads Chat", "member_ids": [alice["user"]["id"]]},
|
||
)
|
||
chat_id = chat_res.json()["id"]
|
||
|
||
with open("tests/fixtures/sample.png", "rb") as f:
|
||
png_data = f.read()
|
||
|
||
async def upload_single(idx: int):
|
||
return await client.post(
|
||
f"/api/v1/chats/{chat_id}/attachments?filename=concurrent_{idx}.png",
|
||
headers={**alice["headers"], "Content-Type": "image/png"},
|
||
content=png_data,
|
||
)
|
||
|
||
tasks = [upload_single(i) for i in range(10)]
|
||
responses = await asyncio.gather(*tasks)
|
||
|
||
for resp in responses:
|
||
assert resp.status_code == 201
|
||
data = resp.json()
|
||
assert data["status"] == "ready"
|
||
assert data["size_bytes"] == len(png_data)
|
||
|
||
stats_cmd = [
|
||
"docker", "stats", "--no-stream", "--format", "{{.Name}}: {{.MemUsage}}",
|
||
"mtusi2026lab4-api-1-1", "mtusi2026lab4-api-2-1"
|
||
]
|
||
stats_res = subprocess.run(stats_cmd, capture_output=True, text=True)
|
||
assert stats_res.returncode == 0
|
||
|
||
|
||
|
||
|