forked from mtusi2026/mtusi2026lab3
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:
co-authored by
Claude Opus 5.5
parent
0ec2f9dae3
commit
416ce4f9db
@@ -0,0 +1,35 @@
|
||||
import asyncio
|
||||
import secrets
|
||||
|
||||
from argon2 import PasswordHasher, Type
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
|
||||
TIME_COST = 2
|
||||
MEMORY_COST_KIB = 19_456
|
||||
PARALLELISM = 1
|
||||
|
||||
|
||||
class Argon2PasswordHasher:
|
||||
__slots__ = ("_dummy", "_hasher", "_slots")
|
||||
|
||||
def __init__(self, concurrency: int) -> None:
|
||||
self._hasher = PasswordHasher(
|
||||
time_cost=TIME_COST,
|
||||
memory_cost=MEMORY_COST_KIB,
|
||||
parallelism=PARALLELISM,
|
||||
type=Type.ID,
|
||||
)
|
||||
self._slots = asyncio.Semaphore(concurrency)
|
||||
self._dummy = self._hasher.hash(secrets.token_urlsafe(16))
|
||||
|
||||
async def hash(self, password: str) -> str:
|
||||
async with self._slots:
|
||||
return await asyncio.to_thread(self._hasher.hash, password)
|
||||
|
||||
async def verify(self, password_hash: str | None, password: str) -> bool:
|
||||
async with self._slots:
|
||||
try:
|
||||
await asyncio.to_thread(self._hasher.verify, password_hash or self._dummy, password)
|
||||
except VerificationError, InvalidHashError:
|
||||
return False
|
||||
return password_hash is not None
|
||||
@@ -0,0 +1,124 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from asyncpg import Record
|
||||
|
||||
from messenger.identity.domain.errors import UsernameAlreadyTaken
|
||||
from messenger.identity.domain.models import Session, User
|
||||
from messenger.identity.domain.values import DisplayName, Username
|
||||
from messenger.shared.infrastructure.postgres import Connection, Database, PostgresUnitOfWork
|
||||
|
||||
INSERT_USER = """
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (username) DO NOTHING
|
||||
RETURNING true
|
||||
"""
|
||||
USER_BY_ID = """
|
||||
SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1
|
||||
"""
|
||||
USER_BY_USERNAME = """
|
||||
SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1
|
||||
"""
|
||||
INSERT_SESSION = """
|
||||
WITH expired AS (DELETE FROM sessions WHERE user_id = $2 AND expires_at <= $3)
|
||||
INSERT INTO sessions (token_hash, user_id, created_at, expires_at) VALUES ($1, $2, $3, $4)
|
||||
"""
|
||||
DELETE_SESSION = "DELETE FROM sessions WHERE token_hash = $1"
|
||||
ACTIVE_SESSION = """
|
||||
SELECT token_hash, user_id, created_at, expires_at
|
||||
FROM sessions
|
||||
WHERE token_hash = $1 AND expires_at > $2
|
||||
"""
|
||||
|
||||
|
||||
def user_of(row: Record | None) -> User | None:
|
||||
if row is None:
|
||||
return None
|
||||
return User(
|
||||
id=row["id"],
|
||||
username=Username(row["username"]),
|
||||
display_name=DisplayName(row["display_name"]),
|
||||
created_at=row["created_at"],
|
||||
password_hash=row["password_hash"],
|
||||
)
|
||||
|
||||
|
||||
class PostgresUserRepository:
|
||||
__slots__ = ("_connection",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
|
||||
async def add(self, user: User) -> None:
|
||||
inserted = await self._connection.fetchval(
|
||||
INSERT_USER,
|
||||
user.id,
|
||||
user.username.value,
|
||||
user.display_name.value,
|
||||
user.password_hash,
|
||||
user.created_at,
|
||||
)
|
||||
if inserted is None:
|
||||
raise UsernameAlreadyTaken("username уже занят")
|
||||
|
||||
|
||||
class PostgresSessionRepository:
|
||||
__slots__ = ("_connection",)
|
||||
|
||||
def __init__(self, connection: Connection) -> None:
|
||||
self._connection = connection
|
||||
|
||||
async def add(self, session: Session) -> None:
|
||||
await self._connection.execute(
|
||||
INSERT_SESSION,
|
||||
session.token_hash,
|
||||
session.user_id,
|
||||
session.created_at,
|
||||
session.expires_at,
|
||||
)
|
||||
|
||||
async def remove(self, token_hash: bytes) -> None:
|
||||
await self._connection.execute(DELETE_SESSION, token_hash)
|
||||
|
||||
|
||||
class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def users(self) -> PostgresUserRepository:
|
||||
return PostgresUserRepository(self.connection)
|
||||
|
||||
@property
|
||||
def sessions(self) -> PostgresSessionRepository:
|
||||
return PostgresSessionRepository(self.connection)
|
||||
|
||||
|
||||
class PostgresUserDirectory:
|
||||
__slots__ = ("_database",)
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
self._database = database
|
||||
|
||||
async def find(self, user_id: UUID) -> User | None:
|
||||
async with self._database.connection() as connection:
|
||||
return user_of(await connection.fetchrow(USER_BY_ID, user_id))
|
||||
|
||||
async def find_by_username(self, username: str) -> User | None:
|
||||
async with self._database.connection() as connection:
|
||||
return user_of(await connection.fetchrow(USER_BY_USERNAME, username))
|
||||
|
||||
|
||||
class PostgresSessionDirectory:
|
||||
__slots__ = ("_database",)
|
||||
|
||||
def __init__(self, database: Database) -> None:
|
||||
self._database = database
|
||||
|
||||
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
|
||||
async with self._database.connection() as connection:
|
||||
row = await connection.fetchrow(ACTIVE_SESSION, token_hash, now)
|
||||
return None if row is None else Session(**dict(row))
|
||||
|
||||
async def invalidate(self, session: Session) -> None:
|
||||
return None
|
||||
@@ -0,0 +1,102 @@
|
||||
import time
|
||||
from collections.abc import Awaitable
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from redis.asyncio import Redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from messenger.identity.application.ports import SessionDirectory
|
||||
from messenger.identity.domain.models import Session
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
REVOKED = "-"
|
||||
FAILURES = (RedisError, OSError)
|
||||
|
||||
|
||||
def key_of(token_hash: bytes) -> str:
|
||||
return f"session:{token_hash.hex()}"
|
||||
|
||||
|
||||
def milliseconds(moment: datetime) -> int:
|
||||
return int(moment.timestamp() * 1000)
|
||||
|
||||
|
||||
def encode(session: Session) -> str:
|
||||
return f"{session.user_id} {session.created_at.isoformat()} {session.expires_at.isoformat()}"
|
||||
|
||||
|
||||
def decode(token_hash: bytes, value: str) -> Session:
|
||||
user_id, created_at, expires_at = value.split(" ")
|
||||
return Session(
|
||||
token_hash=token_hash,
|
||||
user_id=UUID(user_id),
|
||||
created_at=datetime.fromisoformat(created_at),
|
||||
expires_at=datetime.fromisoformat(expires_at),
|
||||
)
|
||||
|
||||
|
||||
class CachedSessionDirectory:
|
||||
__slots__ = ("_client", "_cooldown", "_limit", "_logger", "_origin", "_resume_at")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
origin: SessionDirectory,
|
||||
client: Redis,
|
||||
logger: Logger,
|
||||
*,
|
||||
limit: timedelta,
|
||||
cooldown: float,
|
||||
) -> None:
|
||||
self._origin = origin
|
||||
self._client = client
|
||||
self._logger = logger
|
||||
self._limit = limit
|
||||
self._cooldown = cooldown
|
||||
self._resume_at = 0.0
|
||||
|
||||
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
|
||||
key = key_of(token_hash)
|
||||
cached = await self._read(key)
|
||||
if cached == REVOKED:
|
||||
return None
|
||||
if cached is not None:
|
||||
session = decode(token_hash, cached)
|
||||
return session if session.expires_at > now else None
|
||||
session = await self._origin.find(token_hash, now)
|
||||
if session is not None and self._closed():
|
||||
until = milliseconds(min(session.expires_at, now + self._limit))
|
||||
await self._quietly(self._client.set(key, encode(session), pxat=until, nx=True))
|
||||
return session
|
||||
|
||||
async def invalidate(self, session: Session) -> None:
|
||||
if not self._closed():
|
||||
raise Unavailable("кэш сессий недоступен")
|
||||
try:
|
||||
await self._client.set(
|
||||
key_of(session.token_hash), REVOKED, pxat=milliseconds(session.expires_at)
|
||||
)
|
||||
except FAILURES as error:
|
||||
self._trip(error)
|
||||
raise Unavailable("кэш сессий недоступен") from error
|
||||
|
||||
async def _read(self, key: str) -> str | None:
|
||||
if not self._closed():
|
||||
return None
|
||||
value = await self._quietly(self._client.get(key))
|
||||
return value.decode() if isinstance(value, bytes) else value
|
||||
|
||||
async def _quietly[ResultT](self, call: Awaitable[ResultT]) -> ResultT | None:
|
||||
try:
|
||||
return await call
|
||||
except FAILURES as error:
|
||||
self._trip(error)
|
||||
return None
|
||||
|
||||
def _closed(self) -> bool:
|
||||
return time.monotonic() >= self._resume_at
|
||||
|
||||
def _trip(self, error: Exception) -> None:
|
||||
self._resume_at = time.monotonic() + self._cooldown
|
||||
self._logger.warning("cache.bypassed", error=type(error).__name__, limit=self._cooldown)
|
||||
Reference in New Issue
Block a user