Files
mtusi2026lab7-safronov/service-tests/unit/test_session_service.py
T
ricoromaandClaude Opus 5.5 089d78609d chore: port lab 6 solution into the lab 7 skeleton
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065.
Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public
tests, README, REPORT and evidence of lab 6 are not carried over; infra
and scripts of the lab 7 skeleton stay as they are.
Makefile is the lab 6 one with the lab 7 skeleton part restored
(HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore
are taken from lab 6 because both skeletons have the same files;
.env.example is the lab 6 one without changes.
The compose project, image and CI prefix are renamed to lab7, and
references to the previous lab now name lab6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 03:59:04 +03:00

152 lines
4.7 KiB
Python

"""`SessionService`: вход двумя блоками, отказ одинаков, токен и отзыв."""
from datetime import timedelta
import pytest
from builders import user_dto
from fakes import FakeDatabase, FakeUnitOfWork
from src.core import exceptions, services
from src.core.services import session as session_module
from src.core.services.session import hash_token
from src.schemas import dataclasses
from src.utils.utc import utcnow
pytestmark = pytest.mark.anyio
PASSWORD = "password-1234"
@pytest.fixture(autouse=True)
def cheap_kdf(monkeypatch: pytest.MonkeyPatch, database: FakeDatabase) -> None:
async def verify_password(*, password: str, password_hash: str | None):
database.events.append("kdf")
return password_hash == f"hash:{password}"
monkeypatch.setattr(session_module, "verify_password", verify_password)
async def _user(uow: FakeUnitOfWork) -> dataclasses.UserFullDTO:
user = user_dto(username="alice")
async with uow:
await uow.users.insert_user(
user=user,
password_hash=f"hash:{PASSWORD}",
)
await uow.commit()
return user
async def test_login_two_blocks_kdf_outside(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
user = await _user(uow)
database.events.clear()
result = await services.SessionService(uow).login(
username="alice",
password=PASSWORD,
)
assert result.user == user
assert database.events == [
"enter",
"users.get_user_credentials",
"exit",
"kdf",
"enter",
"sessions.insert_session",
"commit",
"exit",
]
stored = next(iter(database.sessions.values()))
assert stored.token_hash == hash_token(result.token)
@pytest.mark.parametrize(
("username", "password"),
[("alice", "wrong-password"), ("unknown", PASSWORD)],
ids=["wrong_password", "unknown_user"],
)
async def test_login_failure_same_and_no_write_block(
uow: FakeUnitOfWork,
database: FakeDatabase,
username: str,
password: str,
) -> None:
await _user(uow)
database.events.clear()
with pytest.raises(exceptions.InvalidCredentials):
await services.SessionService(uow).login(
username=username,
password=password,
)
# неизвестный пользователь тоже проходит KDF, блока записи нет
assert "kdf" in database.events
assert database.events.count("enter") == 1
assert database.sessions == {}
async def test_authenticate_without_token_opens_no_block(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
with pytest.raises(exceptions.Unauthenticated):
await services.SessionService(uow).authenticate(token=None)
assert database.events == []
async def test_authenticate_valid_expired_unknown(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
user = await _user(uow)
service = services.SessionService(uow)
login = await service.login(username="alice", password=PASSWORD)
current = await service.authenticate(token=login.token)
assert current.user == user
with pytest.raises(exceptions.Unauthenticated):
await service.authenticate(token="unknown-token")
# истёкшая сессия
stored = next(iter(database.sessions.values()))
database.sessions[stored.id] = dataclasses.SessionFullDTO(
id=stored.id,
user_id=stored.user_id,
token_hash=stored.token_hash,
created_at=stored.created_at,
expires_at=utcnow() - timedelta(seconds=1),
)
with pytest.raises(exceptions.Unauthenticated):
await service.authenticate(token=login.token)
async def test_revoke_and_second_revoke(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
await _user(uow)
service = services.SessionService(uow)
login = await service.login(username="alice", password=PASSWORD)
current = await service.authenticate(token=login.token)
await service.revoke(session_id=current.id)
assert database.sessions == {}
# параллельный выход уже удалил: не ошибка
await service.revoke(session_id=current.id)
with pytest.raises(exceptions.Unauthenticated):
await service.authenticate(token=login.token)
async def test_database_failure_on_login_propagates(
uow: FakeUnitOfWork,
database: FakeDatabase,
) -> None:
await _user(uow)
database.fail_on["sessions.insert_session"] = (
exceptions.ServiceUnavailable()
)
with pytest.raises(exceptions.ServiceUnavailable):
await services.SessionService(uow).login(
username="alice",
password=PASSWORD,
)
assert database.sessions == {}