Carry over the lab 2 solution

Bring the application, own tests, Dockerfile, toolchain, compose
stack, migrations, secret generator, restart hook, evidence scripts and
CI job from the lab 2 solution commit 8cddb09 unchanged, merge the lab
2 Makefile targets into the lab 3 skeleton Makefile without touching
its targets, and append the lab 2 solution variables to the skeleton
.env.example. The package version follows the contract version 1.3.0.

This is the starting point of the lab 3 cycle: lint, own tests and the
offline skeleton check pass before any lab 3 change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-28 11:26:15 +03:00
co-authored by Claude Opus 5.5
parent 0ec2f9dae3
commit 416ce4f9db
111 changed files with 7066 additions and 1 deletions
+84
View File
@@ -0,0 +1,84 @@
from uuid import uuid4
from httpx import AsyncClient
from conftest import actor, make_chat, register
async def test_outsider_gets_404_on_chat(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
eve = await register(client, "eve")
chat = await make_chat(client, alice, bob)
response = await client.get(f"/api/v1/chats/{chat['id']}", headers=actor(eve))
assert response.status_code == 404
assert response.json()["error"]["code"] == "not_found"
async def test_unknown_chat_is_indistinguishable_from_foreign(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
foreign = await client.get(f"/api/v1/chats/{chat['id']}", headers=actor(eve))
missing = await client.get(f"/api/v1/chats/{uuid4()}", headers=actor(eve))
assert foreign.status_code == missing.status_code == 404
assert foreign.json()["error"]["code"] == missing.json()["error"]["code"]
assert foreign.json()["error"]["message"] == missing.json()["error"]["message"]
async def test_outsider_cannot_write(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "чужое"},
headers=actor(eve),
)
assert response.status_code == 404
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))
assert history.json()["items"] == []
async def test_outsider_cannot_read_history(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
response = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(eve))
assert response.status_code == 404
async def test_access_checked_before_body(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": ""},
headers=actor(eve),
)
assert response.status_code == 404
async def test_chat_list_hides_foreign_chats(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
eve = await register(client, "eve")
chat = await make_chat(client, alice, bob)
for member in (alice, bob):
listed = await client.get("/api/v1/chats?limit=100", headers=actor(member))
assert any(item["id"] == chat["id"] for item in listed.json()["items"])
hidden = await client.get("/api/v1/chats?limit=100", headers=actor(eve))
assert hidden.json()["items"] == []
async def test_403_is_never_used(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
paths = [
f"/api/v1/chats/{chat['id']}",
f"/api/v1/chats/{chat['id']}/messages",
]
for path in paths:
assert (await client.get(path, headers=actor(eve))).status_code != 403
+242
View File
@@ -0,0 +1,242 @@
import ast
import re
from pathlib import Path
SOURCE = Path(__file__).resolve().parents[2] / "src" / "messenger"
IDENTITY = "messenger.identity"
MESSAGING = "messenger.messaging"
def imports_of(path: Path) -> list[str]:
tree = ast.parse(path.read_text(), filename=str(path))
found: list[str] = []
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.module:
found.append(node.module)
elif isinstance(node, ast.Import):
found.extend(alias.name for alias in node.names)
return found
def modules_under(*parts: str) -> list[Path]:
root = SOURCE.joinpath(*parts)
return [path for path in root.rglob("*.py") if path.name != "__init__.py"]
def test_identity_does_not_know_about_messaging() -> None:
offenders = {
str(path.relative_to(SOURCE)): [m for m in imports_of(path) if m.startswith(MESSAGING)]
for path in modules_under("identity")
}
assert not {k: v for k, v in offenders.items() if v}
def test_messaging_touches_identity_only_through_events() -> None:
allowed = f"{IDENTITY}.domain.events"
offenders: dict[str, list[str]] = {}
for path in modules_under("messaging"):
borrowed = [
module
for module in imports_of(path)
if module.startswith(IDENTITY) and module != allowed
]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders
def test_domains_do_not_import_infrastructure() -> None:
offenders: dict[str, list[str]] = {}
for zone in ("identity", "messaging", "shared"):
for layer in ("domain", "application"):
for path in modules_under(zone, layer):
borrowed = [m for m in imports_of(path) if ".infrastructure" in m]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders
def test_core_layers_do_not_import_pydantic() -> None:
offenders: dict[str, list[str]] = {}
for zone in ("identity", "messaging", "shared"):
for layer in ("domain", "application"):
for path in modules_under(zone, layer):
borrowed = [m for m in imports_of(path) if m.split(".")[0] == "pydantic"]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders, "схемы pydantic живут на границе: в entrypoints/ и config.py"
def test_shared_knows_nothing_about_zones() -> None:
offenders: dict[str, list[str]] = {}
for path in modules_under("shared"):
borrowed = [
module
for module in imports_of(path)
if module.startswith(IDENTITY) or module.startswith(MESSAGING)
]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders
TRANSPORT = ("fastapi", "starlette", "uvicorn", "gunicorn")
def test_shared_core_is_free_of_transport() -> None:
offenders: dict[str, list[str]] = {}
for layer in ("domain", "application", "infrastructure"):
for path in modules_under("shared", layer):
borrowed = [module for module in imports_of(path) if module.split(".")[0] in TRANSPORT]
if borrowed:
offenders[str(path.relative_to(SOURCE))] = borrowed
assert not offenders, "ядро shared обязано жить без веб-фреймворка"
def test_shared_core_holds_only_platform() -> None:
names = {
path.name
for layer in ("domain", "application", "infrastructure")
for path in modules_under("shared", layer)
}
assert names == {
"errors.py",
"events.py",
"commands.py",
"messagebus.py",
"ports.py",
"clock.py",
"ids.py",
"logging.py",
"postgres.py",
}
def test_shared_entrypoints_hold_only_transport() -> None:
names = {path.name for path in modules_under("shared", "entrypoints")}
assert names == {
"actor.py",
"config.py",
"errors.py",
"health.py",
"ioc.py",
"pipeline.py",
"schemas.py",
}
def test_every_zone_owns_its_errors_events_and_commands() -> None:
for zone in ("identity", "messaging"):
assert (SOURCE / zone / "domain" / "errors.py").is_file()
assert (SOURCE / zone / "domain" / "events.py").is_file()
assert (SOURCE / zone / "application" / "commands.py").is_file()
def test_every_zone_owns_its_http_layer() -> None:
for zone in ("identity", "messaging"):
for part in ("http.py", "ioc.py", "errors.py", "journal.py"):
assert (SOURCE / zone / "entrypoints" / part).is_file(), f"{zone}: нет {part}"
def test_only_main_knows_both_zones() -> None:
offenders: dict[str, list[str]] = {}
for path in SOURCE.rglob("*.py"):
relative = path.relative_to(SOURCE)
if path.name in {"__init__.py", "main.py"} or relative.parts[0] in {
"identity",
"messaging",
}:
continue
borrowed = [
module
for module in imports_of(path)
if module.startswith(IDENTITY) or module.startswith(MESSAGING)
]
if borrowed:
offenders[str(relative)] = borrowed
assert not offenders
def test_application_has_no_separate_entrypoints_root() -> None:
assert not (SOURCE / "entrypoints").exists()
assert (SOURCE / "main.py").is_file()
ZONE_WORDS = (
"username",
"display_name",
"chat",
"member",
"history",
"cursor",
"sender",
"message_id",
"message_text",
)
def test_shared_source_mentions_no_domain_vocabulary() -> None:
offenders: dict[str, list[str]] = {}
for path in modules_under("shared"):
source = path.read_text().lower()
hits = sorted({word for word in ZONE_WORDS if word in source})
if hits:
offenders[str(path.relative_to(SOURCE))] = hits
assert not offenders
def test_shared_declares_no_concrete_commands_or_events() -> None:
for path in modules_under("shared"):
tree = ast.parse(path.read_text(), filename=str(path))
declared = [n.name for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]
concrete = [
name
for name in declared
if name not in {"Command", "DomainEvent", "DomainError"}
and (name.endswith("Event") or name in {"RegisterUser", "CreateChat", "PostMessage"})
]
assert not concrete, f"{path.name}: {concrete}"
def test_shared_has_no_test_doubles() -> None:
for path in modules_under("shared"):
source = path.read_text()
for marker in ("Frozen", "Fake", "Stub", "Null", "Dummy"):
assert marker not in source, f"{path.name} содержит подделку {marker}"
def test_zone_errors_do_not_leak_transport_codes() -> None:
for zone in ("identity", "messaging", "shared"):
source = (SOURCE / zone / "domain" / "errors.py").read_text()
assert "http_status" not in source
assert "invalid_request" not in source
assert "404" not in source
IDENTITY_TABLES = ("users", "sessions")
MESSAGING_TABLES = ("chats", "chat_members", "messages")
def sql_tables(zone: str, tables: tuple[str, ...]) -> set[str]:
words: set[str] = set()
for path in modules_under(zone):
tree = ast.parse(path.read_text(), filename=str(path))
for node in ast.walk(tree):
if isinstance(node, ast.Constant) and isinstance(node.value, str):
words.update(re.findall(r"\b(?:FROM|JOIN|INTO|UPDATE)\s+(\w+)", node.value))
return words & set(tables)
def test_sql_of_each_zone_reads_only_its_tables() -> None:
assert sql_tables("messaging", IDENTITY_TABLES) == set()
assert sql_tables("identity", MESSAGING_TABLES) == set()
assert sql_tables("messaging", MESSAGING_TABLES) == set(MESSAGING_TABLES)
assert sql_tables("identity", IDENTITY_TABLES) == set(IDENTITY_TABLES)
def test_messaging_does_not_import_identity_at_all() -> None:
borrowed = {
str(path.relative_to(SOURCE)): [m for m in imports_of(path) if m.startswith(IDENTITY)]
for path in modules_under("messaging")
}
assert not {key: value for key, value in borrowed.items() if value}
+118
View File
@@ -0,0 +1,118 @@
import asyncio
import time
from datetime import datetime
from hashlib import sha256
from redis.asyncio import Redis
from conftest import actor, bearer, register, resolve, running_app, scalar
from messenger.identity.application.ports import SessionDirectory
from messenger.identity.domain.models import Session
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
BEARER = 'Bearer realm="messenger"'
def key_of(token: str) -> str:
return f"session:{sha256(token.encode()).hexdigest()}"
def token_of(user: dict) -> str:
return actor(user)["Authorization"].split()[1]
async def test_second_check_is_served_from_cache(valkey: dict[str, str]) -> None:
cache = Redis.from_url(valkey["url"])
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
hits = (await cache.info("stats"))["keyspace_hits"]
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
assert (await cache.info("stats"))["keyspace_hits"] == hits + 1
key = key_of(token_of(alice))
stored = str(await cache.get(key))
sql = "SELECT expires_at FROM sessions WHERE user_id = $1::uuid"
expires_at: datetime = await scalar(sql, alice["id"])
assert alice["id"] in stored and token_of(alice) not in stored
assert await cache.pexpiretime(key) <= int(expires_at.timestamp() * 1000)
await cache.aclose()
async def test_logout_writes_tombstone_before_database(valkey: dict[str, str]) -> None:
cache = Redis.from_url(valkey["url"])
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
assert (
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
).status_code == 204
assert await cache.get(key_of(token_of(alice))) == b"-"
response = await http.get("/api/v1/users/me", headers=actor(alice))
assert response.status_code == 401
assert response.headers["WWW-Authenticate"] == BEARER
await cache.aclose()
async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, str]) -> None:
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
directory = await resolve(http, SessionDirectory)
assert isinstance(directory, CachedSessionDirectory)
origin = directory._origin
stale: list[Session | None] = []
entered, released = asyncio.Event(), asyncio.Event()
class SlowOrigin:
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
stale.append(await origin.find(token_hash, now))
entered.set()
await released.wait()
return stale[-1]
async def invalidate(self, session: Session) -> None:
await origin.invalidate(session)
directory._origin = SlowOrigin()
reader = asyncio.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
await entered.wait()
directory._origin = origin
assert (
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
).status_code == 204
released.set()
assert (await reader).status_code == 200
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
async def test_flushall_loses_nothing(valkey: dict[str, str]) -> None:
cache = Redis.from_url(valkey["url"])
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
bob = await register(http, "bob")
assert (
await http.delete("/api/v1/auth/sessions/current", headers=actor(bob))
).status_code == 204
await cache.flushall()
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
assert (await http.get("/api/v1/users/me", headers=actor(bob))).status_code == 401
await cache.aclose()
async def test_unreachable_cache_is_bypassed_without_anonymous_access() -> None:
async with running_app(cache_url="redis://127.0.0.1:1/0") as http:
alice = await register(http, "alice")
started = time.perf_counter()
me = await http.get("/api/v1/users/me", headers=actor(alice))
stranger = await http.get("/api/v1/users/me", headers=bearer("x" * 43))
elapsed = time.perf_counter() - started
ready = await http.get("/health/ready")
logout = await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
still = await http.get("/api/v1/users/me", headers=actor(alice))
assert me.json() == alice
assert stranger.status_code == 401
assert stranger.headers["WWW-Authenticate"] == BEARER
assert elapsed < 1
assert ready.status_code == 200
assert logout.status_code == 503
assert logout.json()["error"]["code"] == "unavailable"
assert still.status_code == 200
+88
View File
@@ -0,0 +1,88 @@
import asyncio
from urllib.parse import quote
from uuid import uuid4
from httpx import AsyncClient
from conftest import PASSWORD, actor, make_chat, register
CLIENTS = 10
PER_CLIENT = 10
TOTAL = CLIENTS * PER_CLIENT
async def drain(client: AsyncClient, chat: dict, reader: dict) -> list[dict]:
collected: list[dict] = []
cursor: str | None = None
while True:
query = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
page = (
await client.get(f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader))
).json()
collected.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return collected
async def flood(client: AsyncClient, chat: dict, sender: dict) -> list[int]:
async def writer(worker: int) -> list[int]:
codes = []
for index in range(PER_CLIENT):
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"нагрузка-{worker}-{index}"},
headers=actor(sender),
)
codes.append(response.status_code)
return codes
batches = await asyncio.gather(*(writer(worker) for worker in range(CLIENTS)))
return [code for batch in batches for code in batch]
async def test_hundred_messages_from_ten_clients(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
codes = await flood(client, chat, alice)
assert codes.count(201) == TOTAL, f"неуспешные ответы: {set(codes) - {201}}"
history = await drain(client, chat, bob)
assert len(history) == TOTAL
assert len({item["id"] for item in history}) == TOTAL
assert len({item["text"] for item in history}) == TOTAL
keys = [(item["created_at"], item["id"]) for item in history]
assert keys == sorted(keys), "история не упорядочена по (created_at, id)"
stamps = [item["created_at"] for item in history]
assert len(set(stamps)) == TOTAL, "created_at внутри чата обязан строго возрастать"
async def test_parallel_registration_keeps_username_unique(client: AsyncClient) -> None:
body = {"username": f"race_{uuid4().hex[:12]}", "display_name": "Гонка", "password": PASSWORD}
responses = await asyncio.gather(*(client.post("/api/v1/users", json=body) for _ in range(20)))
codes = [response.status_code for response in responses]
assert codes.count(201) == 1
assert codes.count(409) == len(codes) - 1
async def test_parallel_chat_creation_is_atomic(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
responses = await asyncio.gather(
*(
client.post(
"/api/v1/chats",
json={"title": f"Чат {index}", "member_ids": [alice["id"], bob["id"]]},
headers=actor(alice),
)
for index in range(20)
)
)
assert all(response.status_code == 201 for response in responses)
listed = (await client.get("/api/v1/chats?limit=100", headers=actor(bob))).json()
assert len(listed["items"]) == 20
keys = [(item["created_at"], item["id"]) for item in listed["items"]]
assert keys == sorted(keys)
+188
View File
@@ -0,0 +1,188 @@
import asyncio
from urllib.parse import quote
from uuid import uuid4
from httpx import AsyncClient
from conftest import PASSWORD, actor, make_chat, new_user, register, running_app, scalar
REGISTRATIONS = 25
async def drain_history(client: AsyncClient, chat: dict, reader: dict) -> list[dict]:
collected: list[dict] = []
cursor: str | None = None
while True:
query = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
page = (
await client.get(f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader))
).json()
collected.extend(page["items"])
cursor = page["next_cursor"]
if cursor is None:
return collected
async def test_registration_is_visible_to_chats_immediately() -> None:
async with running_app() as client:
for _ in range(REGISTRATIONS):
user = await register(client, "race")
response = await client.post(
"/api/v1/chats",
json={"title": "Сразу после регистрации", "member_ids": [user["id"]]},
headers=actor(user),
)
assert response.status_code == 201, response.text
async def test_parallel_registrations_are_all_usable_as_members() -> None:
async with running_app() as client:
alice = await register(client, "alice")
bodies = [new_user(f"par{index}") for index in range(REGISTRATIONS)]
responses = await asyncio.gather(
*(client.post("/api/v1/users", json=body) for body in bodies)
)
assert all(response.status_code == 201 for response in responses)
created = [response.json()["id"] for response in responses]
chat = await client.post(
"/api/v1/chats",
json={"title": "Все параллельные", "member_ids": [alice["id"], *created]},
headers=actor(alice),
)
assert chat.status_code == 201, chat.text
assert len(chat.json()["member_ids"]) == REGISTRATIONS + 1
async def test_rejected_registration_leaves_no_trace() -> None:
async with running_app() as client:
alice = await register(client, "alice")
duplicate = await client.post(
"/api/v1/users",
json={"username": alice["username"], "display_name": "Двойник", "password": PASSWORD},
)
assert duplicate.status_code == 409
invalid = await client.post(
"/api/v1/users", json={"username": "AB", "display_name": "", "password": PASSWORD}
)
assert invalid.status_code == 400
sql = "SELECT count(*) FROM users WHERE username = $1"
assert await scalar(sql, alice["username"]) == 1
async def test_failed_chat_creation_rolls_back_both_tables() -> None:
title = f"Откат {uuid4().hex}"
async with running_app() as client:
alice = await register(client, "alice")
before = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json()
rejected = await client.post(
"/api/v1/chats",
json={"title": title, "member_ids": [alice["id"], str(uuid4())]},
headers=actor(alice),
)
assert rejected.status_code == 400
assert rejected.json()["error"]["code"] == "invalid_request"
after = (await client.get("/api/v1/chats?limit=100", headers=actor(alice))).json()
assert after["items"] == before["items"]
assert await scalar("SELECT count(*) FROM chats WHERE title = $1", title) == 0
members = "SELECT count(*) FROM chat_members WHERE user_id = $1::uuid"
assert await scalar(members, alice["id"]) == 0
async def test_rejected_message_does_not_enter_history() -> None:
async with running_app() as client:
alice = await register(client, "alice")
eve = await register(client, "eve")
chat = await make_chat(client, alice)
assert (
await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": " "},
headers=actor(alice),
)
).status_code == 400
assert (
await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "чужое"},
headers=actor(eve),
)
).status_code == 404
assert await drain_history(client, chat, alice) == []
async def test_confirmed_write_is_visible_to_next_read() -> None:
async with running_app() as client:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
for index in range(30):
posted = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"подтверждение {index}"},
headers=actor(alice),
)
assert posted.status_code == 201
history = await drain_history(client, chat, bob)
assert history[-1]["id"] == posted.json()["id"]
assert len(history) == index + 1
async def test_parallel_writes_across_zones_keep_counts_consistent() -> None:
async with running_app() as client:
alice = await register(client, "alice")
chats = [await make_chat(client, alice) for _ in range(4)]
async def writer(chat: dict, worker: int) -> None:
for index in range(10):
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"поток-{worker}-{index}"},
headers=actor(alice),
)
assert response.status_code == 201
async def registrar(index: int) -> str:
return (await register(client, f"parallel{index}"))["id"]
results = await asyncio.gather(
*(writer(chat, number) for number, chat in enumerate(chats)),
*(registrar(index) for index in range(10)),
)
registered = [item for item in results if isinstance(item, str)]
assert len(set(registered)) == 10
for chat in chats:
history = await drain_history(client, chat, alice)
assert len(history) == 10
assert len({item["id"] for item in history}) == 10
keys = [(item["created_at"], item["id"]) for item in history]
assert keys == sorted(keys)
async def test_chat_membership_survives_parallel_reads_and_writes() -> None:
async with running_app() as client:
alice = await register(client, "alice")
bob = await register(client, "bob")
eve = await register(client, "eve")
chat = await make_chat(client, alice, bob)
async def write(index: int) -> None:
await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": f"параллельно {index}"},
headers=actor(alice),
)
async def intruder() -> int:
response = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(eve))
return response.status_code
results = await asyncio.gather(
*(write(index) for index in range(20)),
*(intruder() for _ in range(20)),
)
assert {code for code in results if isinstance(code, int)} == {404}
assert len(await drain_history(client, chat, bob)) == 20
+124
View File
@@ -0,0 +1,124 @@
import asyncio
from dataclasses import fields
from datetime import UTC, datetime
from uuid import uuid4
from httpx import ASGITransport, AsyncClient
from conftest import actor, make_chat, register, split_settings
from fakes import NullLogger
from messenger.identity.domain.events import UserRegistered
from messenger.main import create_app
from messenger.messaging.domain.events import MessagePosted
from messenger.shared.application.messagebus import EventBus, InMemoryEventPublisher
def posted() -> MessagePosted:
return MessagePosted(
message_id=uuid4(),
chat_id=uuid4(),
sender_id=uuid4(),
text_length=5,
created_at=datetime.now(UTC),
)
async def test_event_has_no_message_text() -> None:
names = {field.name for field in fields(posted())}
assert names == {"name", "message_id", "chat_id", "sender_id", "text_length", "created_at"}
async def test_every_subscriber_receives_event() -> None:
bus = EventBus(NullLogger())
seen: list[str] = []
async def first(_event: MessagePosted) -> None:
seen.append("first")
async def second(_event: MessagePosted) -> None:
seen.append("second")
bus.subscribe(MessagePosted, first)
bus.subscribe(MessagePosted, second)
bus.start()
await InMemoryEventPublisher(bus).publish([posted()])
await bus.stop()
assert sorted(seen) == ["first", "second"]
async def test_failing_subscriber_does_not_block_others() -> None:
bus = EventBus(NullLogger())
survived: list[str] = []
async def broken(_event: MessagePosted) -> None:
raise RuntimeError("обработчик упал")
async def healthy(_event: MessagePosted) -> None:
survived.append("ok")
bus.subscribe(MessagePosted, broken)
bus.subscribe(MessagePosted, healthy)
bus.start()
await InMemoryEventPublisher(bus).publish([posted()])
await bus.stop()
assert survived == ["ok"]
async def test_queue_overflow_drops_events_without_raising() -> None:
bus = EventBus(NullLogger(), max_queue=16)
async def never_called(_event: MessagePosted) -> None:
raise AssertionError("обработчик не должен вызываться без запущенной шины")
bus.subscribe(MessagePosted, never_called)
publisher = InMemoryEventPublisher(bus)
await publisher.publish([posted() for _ in range(64)])
assert bus.dropped > 0
assert bus.pending <= 16
async def test_projection_runs_before_publish_returns() -> None:
bus = EventBus(NullLogger())
seen: list[str] = []
async def projection(_event: MessagePosted) -> None:
seen.append("projected")
bus.project(MessagePosted, projection)
await InMemoryEventPublisher(bus).publish([posted()])
assert seen == ["projected"]
async def test_publication_does_not_delay_response() -> None:
app = create_app(**split_settings(log_level="CRITICAL"))
async with (
app.router.lifespan_context(app),
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
):
alice = await register(http, "alice")
chat = await make_chat(http, alice)
bus = await app.state.dishka_container.get(EventBus)
slow = asyncio.Event()
async def blocker(_event: MessagePosted) -> None:
await slow.wait()
bus.subscribe(MessagePosted, blocker)
response = await asyncio.wait_for(
http.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "не ждём обработчик"},
headers=actor(alice),
),
timeout=2,
)
assert response.status_code == 201
slow.set()
async def test_null_logger_hides_everything() -> None:
logger = NullLogger()
logger.info("x", route="/")
logger.warning("x")
logger.error("x")
assert isinstance(UserRegistered, type)
+63
View File
@@ -0,0 +1,63 @@
import asyncpg
import pytest
from conftest import DATABASE, scalar
from messenger.migrate import MigrationChangedError, migrate, migrations
COUNTS = """
SELECT (SELECT count(*) FROM users), (SELECT count(*) FROM sessions),
(SELECT count(*) FROM chats), (SELECT count(*) FROM chat_members),
(SELECT count(*) FROM messages)
"""
async def counts() -> list[int]:
connection = await asyncpg.connect(DATABASE["url"])
try:
return list(await connection.fetchrow(COUNTS))
finally:
await connection.close()
async def test_migrations_are_ordered_and_versioned() -> None:
versions = [version for version, _ in migrations()]
assert versions == sorted(versions)
assert versions[0] == "0001_init"
applied = await scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations")
assert applied == versions
async def test_rerun_changes_nothing() -> None:
before = await counts()
assert await migrate(DATABASE["url"]) == []
assert await counts() == before
async def test_changed_migration_is_refused() -> None:
connection = await asyncpg.connect(DATABASE["url"])
try:
original = await connection.fetchval(
"SELECT checksum FROM schema_migrations WHERE version = '0001_init'"
)
await connection.execute(
"UPDATE schema_migrations SET checksum = 'tampered' WHERE version = '0001_init'"
)
with pytest.raises(MigrationChangedError):
await migrate(DATABASE["url"])
await connection.execute(
"UPDATE schema_migrations SET checksum = $1 WHERE version = '0001_init'", original
)
finally:
await connection.close()
async def test_sender_must_be_member_even_bypassing_api() -> None:
connection = await asyncpg.connect(DATABASE["url"])
try:
with pytest.raises(asyncpg.ForeignKeyViolationError):
await connection.execute(
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
"VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'x', now())"
)
finally:
await connection.close()
+196
View File
@@ -0,0 +1,196 @@
from uuid import uuid4
import pytest
from httpx import AsyncClient
from conftest import PASSWORD, actor, make_chat, register
ERROR_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
}
def assert_error(response, expected_status: int) -> None:
assert response.status_code == expected_status, response.text
assert response.headers.get("content-type", "").startswith("application/json")
body = response.json()
assert set(body) == {"error"}
assert set(body["error"]) == {"code", "message", "request_id"}
assert body["error"]["code"] == ERROR_CODES[expected_status]
assert body["error"]["message"]
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
async def test_malformed_json(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users",
content=b'{"username": ',
headers={"Content-Type": "application/json"},
)
assert_error(response, 400)
async def test_unexpected_field(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users",
json={"username": "abc_def", "display_name": "X", "password": PASSWORD, "role": "admin"},
)
assert_error(response, 400)
async def test_wrong_types(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/users", json={"username": 1, "display_name": True, "password": 12345678901234}
)
assert_error(response, 400)
@pytest.mark.parametrize(
"body",
[
{"username": "Alice", "display_name": "X", "password": PASSWORD},
{"username": "ab", "display_name": "X", "password": PASSWORD},
{"username": "alice_01\n", "display_name": "X", "password": PASSWORD},
{"username": "abc_def", "display_name": "", "password": PASSWORD},
{"username": "abc_def", "display_name": " ", "password": PASSWORD},
{"username": "abc_def", "display_name": "x" * 101, "password": PASSWORD},
{"username": "abc_def", "display_name": "X", "password": "short"},
{"username": "abc_def", "display_name": "X", "password": "x" * 129},
{"username": "abc_def", "display_name": "X", "password": " " * 20},
{"username": "abc_def", "display_name": "X"},
{"username": "abc_def", "password": PASSWORD},
],
)
async def test_invalid_registration(client: AsyncClient, body: dict) -> None:
assert_error(await client.post("/api/v1/users", json=body), 400)
async def test_duplicate_username(client: AsyncClient) -> None:
alice = await register(client, "alice")
repeat = await client.post(
"/api/v1/users",
json={"username": alice["username"], "display_name": "Другая", "password": PASSWORD},
)
assert_error(repeat, 409)
async def test_missing_identity(client: AsyncClient) -> None:
assert_error(await client.get("/api/v1/users/me"), 401)
BAD_AUTHORIZATIONS = [
"",
"Bearer",
"Bearer ",
"Bearer not a token",
"Bearer " + "x" * 43,
"Token abcdef",
"11111111-1111-4111-8111-111111111111",
]
@pytest.mark.parametrize("raw", BAD_AUTHORIZATIONS)
async def test_invalid_bearer(client: AsyncClient, raw: str) -> None:
response = await client.get("/api/v1/users/me", headers={"Authorization": raw})
assert_error(response, 401)
assert response.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
async def test_user_id_header_alone_is_ignored(client: AsyncClient) -> None:
alice = await register(client, "alice")
response = await client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]})
assert_error(response, 401)
async def test_identity_checked_before_body(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/chats",
content=b"{broken",
headers={"Content-Type": "application/json"},
)
assert_error(response, 401)
async def test_empty_message_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
for text in ("", " ", "\n\t"):
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": text},
headers=actor(alice),
)
assert_error(response, 400)
async def test_long_message_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "я" * 4001},
headers=actor(alice),
)
assert_error(response, 400)
async def test_sender_id_not_accepted(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "подмена", "sender_id": bob["id"]},
headers=actor(alice),
)
assert_error(response, 400)
@pytest.mark.parametrize(
"body",
[
{"title": "Чат", "member_ids": []},
{"title": "", "member_ids": None},
{"title": " ", "member_ids": None},
{"title": "Чат", "member_ids": ["не-uuid"]},
{"title": "Чат", "member_ids": [1]},
{"title": "Чат", "member_ids": "не-список"},
],
)
async def test_invalid_chat_creation(client: AsyncClient, body: dict) -> None:
alice = await register(client, "alice")
payload = dict(body)
if payload["member_ids"] is None:
payload["member_ids"] = [alice["id"]]
response = await client.post("/api/v1/chats", json=payload, headers=actor(alice))
assert_error(response, 400)
async def test_creator_must_be_member(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
response = await client.post(
"/api/v1/chats",
json={"title": "Чат", "member_ids": [bob["id"]]},
headers=actor(alice),
)
assert_error(response, 400)
async def test_unknown_member_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
response = await client.post(
"/api/v1/chats",
json={"title": "Чат", "member_ids": [alice["id"], str(uuid4())]},
headers=actor(alice),
)
assert_error(response, 400)
async def test_bad_chat_id_in_path(client: AsyncClient) -> None:
alice = await register(client, "alice")
assert_error(await client.get("/api/v1/chats/не-uuid", headers=actor(alice)), 400)
+144
View File
@@ -0,0 +1,144 @@
import json
import time
from uuid import uuid4
from httpx import ASGITransport, AsyncClient
from conftest import PASSWORD, actor, make_chat, register, running_app, split_settings
from messenger.main import create_app
MARKER_TEXT = "маркер-который-не-должен-попасть-в-логи-9f3a"
async def test_health_needs_no_identity(client: AsyncClient) -> None:
for path in ("/health/live", "/health/ready"):
response = await client.get(path)
assert response.status_code == 200
assert response.json() == {"status": "ok"}
assert response.headers["X-Request-Id"]
async def test_every_response_carries_request_id(client: AsyncClient) -> None:
alice = await register(client, "alice")
probes = [
await client.get("/health/live"),
await client.get("/api/v1/users/me", headers=actor(alice)),
await client.get("/api/v1/users/me"),
await client.get(f"/api/v1/chats/{uuid4()}", headers=actor(alice)),
await client.get("/api/v1/unknown-path"),
]
assert all(probe.headers.get("X-Request-Id") for probe in probes)
async def test_client_request_id_is_preserved(client: AsyncClient) -> None:
response = await client.get("/health/live", headers={"X-Request-Id": "trace-42"})
assert response.headers["X-Request-Id"] == "trace-42"
async def test_unknown_public_route_is_404(client: AsyncClient) -> None:
response = await client.get("/nothing-here")
assert response.status_code == 404
assert response.json()["error"]["code"] == "not_found"
async def test_unknown_protected_route_needs_identity(client: AsyncClient) -> None:
anonymous = await client.get("/api/v1/unknown-path")
assert anonymous.status_code == 401
assert set(anonymous.json()["error"]) == {"code", "message", "request_id"}
alice = await register(client, "alice")
identified = await client.get("/api/v1/unknown-path", headers=actor(alice))
assert identified.status_code == 404
async def test_method_not_allowed_is_hidden(client: AsyncClient) -> None:
response = await client.delete("/health/live")
assert response.status_code == 404
assert response.json()["error"]["code"] == "not_found"
async def test_logs_do_not_contain_message_text(capsys) -> None:
app = create_app(**split_settings(log_level="INFO"))
async with (
app.router.lifespan_context(app),
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
):
alice = await register(http, "alice")
chat = await make_chat(http, alice)
response = await http.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": MARKER_TEXT},
headers=actor(alice),
)
assert response.status_code == 201
captured = capsys.readouterr()
assert MARKER_TEXT not in captured.out
assert MARKER_TEXT not in captured.err
assert alice["display_name"] not in captured.out
assert any("request.handled" in line for line in captured.out.splitlines())
async def test_log_lines_are_json(capsys) -> None:
app = create_app(**split_settings(log_level="INFO"))
async with (
app.router.lifespan_context(app),
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
):
await http.get("/health/live")
for line in capsys.readouterr().out.splitlines():
record = json.loads(line)
assert {"ts", "level", "event"} <= set(record)
async def test_body_limit_returns_413() -> None:
app = create_app(**split_settings(max_body_bytes=4096))
async with (
app.router.lifespan_context(app),
AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as http,
):
response = await http.post("/api/v1/users", content=b"x" * 5000)
assert response.status_code == 413
assert response.json()["error"]["code"] == "payload_too_large"
async def test_ready_turns_unavailable_without_database() -> None:
async with running_app(database_url="postgresql://u:p@127.0.0.1:1/none") as http:
started = time.perf_counter()
ready = await http.get("/health/ready")
live = await http.get("/health/live")
elapsed = time.perf_counter() - started
assert ready.status_code == 503
assert ready.json()["error"]["code"] == "unavailable"
assert live.status_code == 200
assert elapsed < 2
async def test_protected_request_is_503_not_401_without_database() -> None:
async with running_app(database_url="postgresql://u:p@127.0.0.1:1/none") as http:
response = await http.get(
"/api/v1/users/me", headers={"Authorization": "Bearer " + "x" * 43}
)
assert response.status_code == 503
assert response.json()["error"]["code"] == "unavailable"
assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
async def test_state_survives_new_process() -> None:
async with running_app() as http:
alice = await register(http, "alice")
chat = await make_chat(http, alice)
async with running_app() as http:
me = await http.get("/api/v1/users/me", headers=actor(alice))
listed = await http.get("/api/v1/chats?limit=100", headers=actor(alice))
assert me.json() == alice
assert [item["id"] for item in listed.json()["items"]] == [chat["id"]]
async def test_logs_do_not_contain_credentials(capsys) -> None:
async with running_app(log_level="INFO") as http:
alice = await register(http, "secret")
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
output = capsys.readouterr()
captured = output.out + output.err
assert PASSWORD not in captured
assert actor(alice)["Authorization"].split()[1] not in captured
assert "audit.session_opened" in captured
+155
View File
@@ -0,0 +1,155 @@
from urllib.parse import quote
import pytest
from httpx import AsyncClient
from conftest import actor, make_chat, register
TOTAL = 12
async def fill(client: AsyncClient, chat: dict, sender: dict, count: int) -> list[str]:
texts = []
for index in range(count):
text = f"сообщение {index:02d}"
response = await client.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": text},
headers=actor(sender),
)
assert response.status_code == 201, response.text
texts.append(text)
return texts
async def walk(client: AsyncClient, chat: dict, reader: dict, limits: list[int]) -> list[str]:
collected: list[str] = []
cursor: str | None = None
step = 0
while True:
limit = limits[min(step, len(limits) - 1)]
query = f"?limit={limit}"
if cursor:
query += f"&cursor={quote(cursor, safe='')}"
response = await client.get(
f"/api/v1/chats/{chat['id']}/messages{query}", headers=actor(reader)
)
assert response.status_code == 200, response.text
page = response.json()
assert len(page["items"]) <= limit
collected.extend(item["text"] for item in page["items"])
cursor = page["next_cursor"]
step += 1
if cursor is None:
return collected
async def test_full_walk_has_no_gaps_or_repeats(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
expected = await fill(client, chat, alice, TOTAL)
assert await walk(client, chat, bob, [5]) == expected
async def test_limit_may_change_between_pages(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
expected = await fill(client, chat, alice, TOTAL)
assert await walk(client, chat, alice, [1, 7, 3, 100]) == expected
async def test_last_page_closes_history(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await fill(client, chat, alice, 2)
first = (
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=2", headers=actor(alice))
).json()
assert len(first["items"]) == 2
assert first["next_cursor"] is None
async def test_cursor_is_shared_between_members(client: AsyncClient) -> None:
alice = await register(client, "alice")
bob = await register(client, "bob")
chat = await make_chat(client, alice, bob)
await fill(client, chat, alice, 3)
page = (
await client.get(f"/api/v1/chats/{chat['id']}/messages?limit=1", headers=actor(alice))
).json()
cursor = quote(page["next_cursor"], safe="")
response = await client.get(
f"/api/v1/chats/{chat['id']}/messages?limit=1&cursor={cursor}", headers=actor(bob)
)
assert response.status_code == 200
async def test_cursor_from_another_chat_is_rejected(client: AsyncClient) -> None:
alice = await register(client, "alice")
first = await make_chat(client, alice)
second = await make_chat(client, alice)
await fill(client, first, alice, 3)
await fill(client, second, alice, 3)
page = (
await client.get(f"/api/v1/chats/{first['id']}/messages?limit=1", headers=actor(alice))
).json()
cursor = quote(page["next_cursor"], safe="")
response = await client.get(
f"/api/v1/chats/{second['id']}/messages?limit=1&cursor={cursor}", headers=actor(alice)
)
assert response.status_code == 400
assert response.json()["error"]["code"] == "invalid_request"
@pytest.mark.parametrize("cursor", ["garbage", "1.2.3.4", "%20"])
async def test_broken_cursor_is_rejected(client: AsyncClient, cursor: str) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
response = await client.get(
f"/api/v1/chats/{chat['id']}/messages?cursor={cursor}", headers=actor(alice)
)
assert response.status_code == 400
@pytest.mark.parametrize("limit", ["0", "-1", "101", "abc", "1.5", ""])
async def test_limit_out_of_range(client: AsyncClient, limit: str) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
response = await client.get(f"{path}?limit={limit}", headers=actor(alice))
assert response.status_code == 400, f"{path}?limit={limit} → {response.status_code}"
async def test_default_limit_is_50(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await fill(client, chat, alice, 51)
page = (await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(alice))).json()
assert len(page["items"]) == 50
assert page["next_cursor"] is not None
async def test_unknown_query_parameter_is_ignored(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
await fill(client, chat, alice, 2)
for path in (f"/api/v1/chats/{chat['id']}/messages", "/api/v1/chats"):
response = await client.get(f"{path}?limit=1&unknown=x", headers=actor(alice))
assert response.status_code == 200, response.text
assert len(response.json()["items"]) == 1
async def test_chat_list_pagination(client: AsyncClient) -> None:
alice = await register(client, "alice")
created = [(await make_chat(client, alice))["id"] for _ in range(5)]
collected: list[str] = []
cursor: str | None = None
while True:
query = "?limit=2" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
page = (await client.get(f"/api/v1/chats{query}", headers=actor(alice))).json()
collected.extend(item["id"] for item in page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
assert collected == created
+27
View File
@@ -0,0 +1,27 @@
import time
from conftest import actor, register, resolve, running_app
from messenger.shared.infrastructure.postgres import Database
async def test_exhausted_pool_answers_503_in_bounded_time() -> None:
async with running_app(db_pool_max_size=1, db_acquire_timeout_seconds=0.3) as http:
alice = await register(http, "alice")
database = await resolve(http, Database)
async with database.connection():
started = time.perf_counter()
starved = await http.get("/api/v1/users/me", headers=actor(alice))
elapsed = time.perf_counter() - started
recovered = await http.get("/api/v1/users/me", headers=actor(alice))
assert starved.status_code == 503
assert starved.json()["error"]["code"] == "unavailable"
assert 0.25 < elapsed < 1
assert recovered.json() == alice
async def test_statement_timeout_is_set_on_connections() -> None:
async with running_app(db_command_timeout_seconds=1.5) as http:
database = await resolve(http, Database)
async with database.connection() as connection:
assert await connection.fetchval("SHOW statement_timeout") == "1500ms"
assert await connection.fetchval("SHOW lock_timeout") == "1500ms"
+172
View File
@@ -0,0 +1,172 @@
import asyncio
from datetime import datetime, timedelta
import pytest
from httpx import AsyncClient
from conftest import (
PASSWORD,
actor,
basic,
bearer,
login,
make_chat,
new_user,
register,
running_app,
scalar,
)
BASIC = 'Basic realm="messenger", charset="UTF-8"'
BEARER = 'Bearer realm="messenger"'
def challenged(response, challenge: str) -> None:
assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == challenge
assert response.json()["error"]["code"] == "unauthorized"
assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
async def test_login_returns_session_for_registered_user(client: AsyncClient) -> None:
body = new_user("alice")
user = (await client.post("/api/v1/users", json=body)).json()
session = await login(client, body["username"])
assert set(session) == {"token", "token_type", "expires_at", "user"}
assert session["token_type"] == "Bearer"
assert session["user"] == user
assert len(session["token"]) >= 43
assert body["username"] not in session["token"] and user["id"] not in session["token"]
assert session["expires_at"].endswith("Z")
expires = datetime.fromisoformat(session["expires_at"])
created = datetime.fromisoformat(user["created_at"])
assert timedelta(seconds=3500) < expires - created < timedelta(seconds=3700)
async def test_registration_response_hides_password(client: AsyncClient) -> None:
body = new_user("alice")
response = await client.post("/api/v1/users", json=body)
assert set(response.json()) == {"id", "username", "display_name", "created_at"}
assert PASSWORD not in response.text
async def test_password_is_stored_as_argon2id(client: AsyncClient) -> None:
alice = await register(client, "alice")
stored = await scalar("SELECT password_hash FROM users WHERE id = $1::uuid", alice["id"])
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
assert PASSWORD not in stored
async def test_session_stores_only_token_digest(client: AsyncClient) -> None:
alice = await register(client, "alice")
token = actor(alice)["Authorization"].split()[1]
sql = "SELECT count(*) FROM sessions WHERE token_hash = sha256(convert_to($1, 'UTF8'))"
assert await scalar(sql, token) == 1
raw = "SELECT count(*) FROM sessions WHERE encode(token_hash, 'escape') = $1"
assert await scalar(raw, token) == 0
async def test_wrong_password_and_unknown_user_look_the_same(client: AsyncClient) -> None:
alice = await register(client, "alice")
wrong = await client.post("/api/v1/auth/sessions", headers=basic(alice["username"], "x" * 20))
unknown = await client.post("/api/v1/auth/sessions", headers=basic("u_ghost_000", PASSWORD))
challenged(wrong, BASIC)
challenged(unknown, BASIC)
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
@pytest.mark.parametrize(
"headers",
[{}, {"Authorization": "Basic !!!"}, {"Authorization": "Bearer abc"}, {"X-User-Id": "x"}],
)
async def test_login_without_valid_basic(client: AsyncClient, headers: dict) -> None:
challenged(await client.post("/api/v1/auth/sessions", headers=headers), BASIC)
async def test_password_with_colon_logs_in(client: AsyncClient) -> None:
body = new_user("colon", password="пароль:с:двоеточием")
assert (await client.post("/api/v1/users", json=body)).status_code == 201
assert (await login(client, body["username"], body["password"]))["token"]
async def test_login_with_body_is_rejected(client: AsyncClient) -> None:
body = new_user("body")
await client.post("/api/v1/users", json=body)
response = await client.post(
"/api/v1/auth/sessions", headers=basic(body["username"], PASSWORD), json={"x": 1}
)
assert response.status_code == 400
assert response.json()["error"]["code"] == "invalid_request"
async def test_basic_on_business_endpoint_gets_bearer_challenge(client: AsyncClient) -> None:
body = new_user("alice")
await client.post("/api/v1/users", json=body)
challenged(
await client.get("/api/v1/users/me", headers=basic(body["username"], PASSWORD)), BEARER
)
async def test_user_id_header_does_not_override_owner(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
response = await client.get(
"/api/v1/users/me", headers={**actor(alice), "X-User-Id": eve["id"]}
)
assert response.json() == alice
async def test_authentication_precedes_validation(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/chats/not-a-uuid/messages",
content=b"{broken",
headers={"Content-Type": "application/json"},
)
challenged(response, BEARER)
async def test_logout_revokes_only_current_session(client: AsyncClient) -> None:
body = new_user("alice")
await client.post("/api/v1/users", json=body)
first = (await login(client, body["username"]))["token"]
second = (await login(client, body["username"]))["token"]
logout = await client.delete("/api/v1/auth/sessions/current", headers=bearer(first))
assert logout.status_code == 204
assert logout.content == b""
assert logout.headers["X-Request-Id"]
challenged(await client.get("/api/v1/users/me", headers=bearer(first)), BEARER)
challenged(await client.delete("/api/v1/auth/sessions/current", headers=bearer(first)), BEARER)
assert (await client.get("/api/v1/users/me", headers=bearer(second))).status_code == 200
async def test_short_ttl_session_expires() -> None:
async with running_app(session_ttl_seconds=1) as client:
alice = await register(client, "alice")
assert (await client.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
await asyncio.sleep(1.2)
challenged(await client.get("/api/v1/users/me", headers=actor(alice)), BEARER)
async def test_expired_sessions_are_purged_on_next_login() -> None:
async with running_app(session_ttl_seconds=1) as client:
body = new_user("purge")
user = (await client.post("/api/v1/users", json=body)).json()
await login(client, body["username"])
await asyncio.sleep(1.2)
await login(client, body["username"])
sql = "SELECT count(*) FROM sessions WHERE user_id = $1::uuid"
assert await scalar(sql, user["id"]) == 1
async def test_chat_routes_require_bearer(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
for method, path in [
("GET", "/api/v1/chats"),
("POST", "/api/v1/chats"),
("GET", f"/api/v1/chats/{chat['id']}"),
("GET", f"/api/v1/chats/{chat['id']}/messages"),
("POST", f"/api/v1/chats/{chat['id']}/messages"),
("DELETE", "/api/v1/auth/sessions/current"),
]:
challenged(await client.request(method, path, headers={"X-User-Id": alice["id"]}), BEARER)
+97
View File
@@ -0,0 +1,97 @@
import asyncio
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from httpx import AsyncClient
from conftest import actor, make_chat, register, resolve, running_app
from messenger.messaging.application import handlers
from messenger.messaging.domain.events import MessagePosted
from messenger.shared.application.messagebus import EventBus
MARKER = "текст-который-не-должен-утечь-при-таймауте"
@asynccontextmanager
async def slow_post(delay: float) -> AsyncIterator[None]:
original: Callable = handlers.PostMessageHandler.__call__
async def stalled(self, command):
await asyncio.sleep(delay)
return await original(self, command)
handlers.PostMessageHandler.__call__ = stalled
try:
yield
finally:
handlers.PostMessageHandler.__call__ = original
async def post(client: AsyncClient, chat: dict, sender: dict, text: str):
return await client.post(
f"/api/v1/chats/{chat['id']}/messages", json={"text": text}, headers=actor(sender)
)
async def prepared(client: AsyncClient) -> tuple[dict, dict]:
alice = await register(client, "alice")
return alice, await make_chat(client, alice)
async def test_timeout_returns_unavailable_error_body() -> None:
async with running_app(request_timeout_seconds=0.15) as client:
alice, chat = await prepared(client)
async with slow_post(1.0):
response = await post(client, chat, alice, "медленная запись")
assert response.status_code == 503
body = response.json()
assert body["error"]["code"] == "unavailable"
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
async def test_timeout_does_not_break_following_requests() -> None:
async with running_app(request_timeout_seconds=0.15) as client:
alice, chat = await prepared(client)
async with slow_post(1.0):
assert (await post(client, chat, alice, "зависшая запись")).status_code == 503
assert (await post(client, chat, alice, "нормальная запись")).status_code == 201
assert (await client.get("/health/ready")).status_code == 200
async def test_timeout_is_logged_without_message_text(capsys) -> None:
async with running_app(request_timeout_seconds=0.15, log_level="INFO") as client:
alice, chat = await prepared(client)
async with slow_post(1.0):
assert (await post(client, chat, alice, MARKER)).status_code == 503
captured = capsys.readouterr()
assert "request.timeout" in captured.out
assert MARKER not in captured.out
assert MARKER not in captured.err
async def test_normal_request_is_not_affected_by_timeout() -> None:
async with running_app(request_timeout_seconds=5.0) as client:
alice, chat = await prepared(client)
assert (await post(client, chat, alice, "обычная запись")).status_code == 201
async def test_slow_event_handler_does_not_trigger_timeout() -> None:
async with running_app(request_timeout_seconds=0.3) as client:
alice, chat = await prepared(client)
blocked = asyncio.Event()
bus = await resolve(client, EventBus)
async def stall(_event: MessagePosted) -> None:
await blocked.wait()
bus.subscribe(MessagePosted, stall)
response = await post(client, chat, alice, "ответ не ждёт обработчик")
blocked.set()
assert response.status_code == 201
async def test_healthcheck_stays_fast(client: AsyncClient) -> None:
loop = asyncio.get_running_loop()
started = loop.time()
assert (await client.get("/health/live")).status_code == 200
assert loop.time() - started < 1.0
+67
View File
@@ -0,0 +1,67 @@
import json
import re
from datetime import UTC, datetime
from typing import Any
import pytest
from httpx import Response
from conftest import bearer, login, new_user, running_app
from messenger.shared.infrastructure.clock import MonotonicUtcClock
RFC3339_UTC = re.compile(r"\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z\Z")
MOMENTS = [
datetime(2026, 10, 12, 8, 49, 2, tzinfo=UTC),
datetime(2026, 10, 12, 8, 49, 2, 120, tzinfo=UTC),
]
def assert_wire(response: Response, expected: dict[str, Any]) -> None:
assert (
response.content == json.dumps(expected, ensure_ascii=False, separators=(",", ":")).encode()
)
@pytest.mark.parametrize("moment", MOMENTS, ids=["whole-second", "microseconds"])
async def test_created_at_is_rfc3339_utc(monkeypatch: pytest.MonkeyPatch, moment: datetime) -> None:
monkeypatch.setattr(MonotonicUtcClock, "now", lambda _self: moment)
stamp = moment.isoformat().replace("+00:00", "Z")
assert RFC3339_UTC.match(stamp)
async with running_app() as http:
body = new_user("wire")
response = await http.post("/api/v1/users", json=body)
user_id = response.json()["id"]
user = {
"id": user_id,
"username": body["username"],
"display_name": body["display_name"],
"created_at": stamp,
}
assert_wire(response, user)
session = await login(http, body["username"])
headers = bearer(session["token"])
assert session["user"] == user
assert_wire(await http.get("/api/v1/users/me", headers=headers), user)
response = await http.post(
"/api/v1/chats", json={"title": "Чат", "member_ids": [user_id]}, headers=headers
)
chat_id = response.json()["id"]
chat = {"id": chat_id, "title": "Чат", "member_ids": [user_id], "created_at": stamp}
assert_wire(response, chat)
assert_wire(await http.get(f"/api/v1/chats/{chat_id}", headers=headers), chat)
listed = await http.get("/api/v1/chats", headers=headers)
assert_wire(listed, {"items": [chat], "next_cursor": None})
path = f"/api/v1/chats/{chat_id}/messages"
response = await http.post(path, json={"text": "привет"}, headers=headers)
message = {
"id": response.json()["id"],
"chat_id": chat_id,
"sender_id": user_id,
"text": "привет",
"created_at": stamp,
}
assert_wire(response, message)
history = await http.get(path, headers=headers)
assert_wire(history, {"items": [message], "next_cursor": None})