forked from mtusi2026/mtusi2026lab2
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,98 @@
|
||||
import re
|
||||
from base64 import b64decode
|
||||
from binascii import Error as Base64Error
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from starlette.types import Scope
|
||||
|
||||
from messenger.identity.application.queries import Authenticate, VerifyCredentials
|
||||
from messenger.identity.domain.models import Session, User
|
||||
from messenger.shared.entrypoints.errors import Unauthenticated
|
||||
from messenger.shared.entrypoints.pipeline import Rejection, header
|
||||
|
||||
LOGIN_PATH = "/api/v1/auth/sessions"
|
||||
PROTECTED_PREFIX = "/api/v1/"
|
||||
PUBLIC_ROUTES = frozenset({("POST", "/api/v1/users")})
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
AUTHORIZATION = b"authorization"
|
||||
TOKEN = re.compile(r"[A-Za-z0-9\-._~+/]{1,512}=*")
|
||||
|
||||
|
||||
def normalized(path: str) -> str:
|
||||
return path.rstrip("/") or "/"
|
||||
|
||||
|
||||
def challenge_for(path: str) -> str:
|
||||
return BASIC_CHALLENGE if normalized(path) == LOGIN_PATH else BEARER_CHALLENGE
|
||||
|
||||
|
||||
def basic_credentials(value: str) -> tuple[str, str] | None:
|
||||
scheme, _, encoded = value.partition(" ")
|
||||
if scheme.lower() != "basic":
|
||||
return None
|
||||
try:
|
||||
decoded = b64decode(encoded.strip(), validate=True).decode("utf-8")
|
||||
except Base64Error, UnicodeDecodeError:
|
||||
return None
|
||||
username, separator, password = decoded.partition(":")
|
||||
if not separator or not username.isascii():
|
||||
return None
|
||||
return username, password
|
||||
|
||||
|
||||
def bearer_token(value: str) -> str | None:
|
||||
scheme, _, token = value.partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or TOKEN.fullmatch(token) is None:
|
||||
return None
|
||||
return token
|
||||
|
||||
|
||||
def rejection(path: str) -> Rejection:
|
||||
return Rejection(401, "unauthorized", (("www-authenticate", challenge_for(path)),))
|
||||
|
||||
|
||||
async def guard(scope: Scope) -> Rejection | None:
|
||||
method, path = scope["method"], normalized(scope["path"])
|
||||
if not path.startswith(PROTECTED_PREFIX) or (method, path) in PUBLIC_ROUTES:
|
||||
return None
|
||||
container = scope["app"].state.dishka_container
|
||||
state = scope.setdefault("state", {})
|
||||
raw = header(scope, AUTHORIZATION)
|
||||
if (method, path) == ("POST", LOGIN_PATH):
|
||||
credentials = basic_credentials(raw)
|
||||
verify = await container.get(VerifyCredentials)
|
||||
user = await verify(*credentials) if credentials else None
|
||||
if user is None:
|
||||
return rejection(path)
|
||||
state["user"] = user
|
||||
state["actor"] = user.id
|
||||
return None
|
||||
token = bearer_token(raw)
|
||||
authenticate = await container.get(Authenticate)
|
||||
session = await authenticate(token) if token else None
|
||||
if session is None:
|
||||
return rejection(path)
|
||||
state["session"] = session
|
||||
state["actor"] = session.user_id
|
||||
return None
|
||||
|
||||
|
||||
async def verified_user(request: Request) -> User:
|
||||
user = getattr(request.state, "user", None)
|
||||
if not isinstance(user, User):
|
||||
raise Unauthenticated("учётные данные не подтверждены")
|
||||
return user
|
||||
|
||||
|
||||
async def current_session(request: Request) -> Session:
|
||||
session = getattr(request.state, "session", None)
|
||||
if not isinstance(session, Session):
|
||||
raise Unauthenticated("сессия не подтверждена")
|
||||
return session
|
||||
|
||||
|
||||
type VerifiedUser = Annotated[User, Depends(verified_user)]
|
||||
type CurrentSession = Annotated[Session, Depends(current_session)]
|
||||
@@ -0,0 +1,12 @@
|
||||
from messenger.identity.domain.errors import (
|
||||
ActorNotIdentified,
|
||||
InvalidUserData,
|
||||
UsernameAlreadyTaken,
|
||||
)
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
|
||||
ERROR_CODES: dict[type[DomainError], tuple[str, int]] = {
|
||||
InvalidUserData: ("invalid_request", 400),
|
||||
UsernameAlreadyTaken: ("conflict", 409),
|
||||
ActorNotIdentified: ("unauthorized", 401),
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
from dishka.integrations.fastapi import FromDishka, inject
|
||||
from fastapi import APIRouter, Request, Response, status
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
|
||||
from messenger.identity.application.bus import IdentityCommandBus
|
||||
from messenger.identity.application.commands import CloseSession, OpenSession, RegisterUser
|
||||
from messenger.identity.application.queries import GetCurrentUser
|
||||
from messenger.identity.entrypoints.authentication import CurrentSession, VerifiedUser
|
||||
from messenger.identity.entrypoints.schemas import CreateUserRequest, SessionOut, UserOut
|
||||
from messenger.shared.entrypoints.actor import Actor
|
||||
|
||||
router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||
sessions_router = APIRouter(prefix="/api/v1/auth/sessions", tags=["sessions"])
|
||||
|
||||
|
||||
@router.post("", status_code=status.HTTP_201_CREATED)
|
||||
@inject
|
||||
async def create_user(
|
||||
body: CreateUserRequest,
|
||||
bus: FromDishka[IdentityCommandBus],
|
||||
) -> UserOut:
|
||||
user = await bus.execute(
|
||||
RegisterUser(username=body.username, display_name=body.display_name, password=body.password)
|
||||
)
|
||||
return UserOut.of(user)
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
@inject
|
||||
async def current_user(
|
||||
actor: Actor,
|
||||
query: FromDishka[GetCurrentUser],
|
||||
) -> UserOut:
|
||||
return UserOut.of(await query(actor))
|
||||
|
||||
|
||||
@sessions_router.post("", status_code=status.HTTP_201_CREATED)
|
||||
@inject
|
||||
async def open_session(
|
||||
request: Request,
|
||||
user: VerifiedUser,
|
||||
bus: FromDishka[IdentityCommandBus],
|
||||
) -> SessionOut:
|
||||
if await request.body():
|
||||
raise RequestValidationError([])
|
||||
token, session = await bus.execute(OpenSession(user_id=user.id))
|
||||
return SessionOut.of(token, session, user)
|
||||
|
||||
|
||||
@sessions_router.delete("/current", status_code=status.HTTP_204_NO_CONTENT)
|
||||
@inject
|
||||
async def close_session(
|
||||
session: CurrentSession,
|
||||
bus: FromDishka[IdentityCommandBus],
|
||||
) -> Response:
|
||||
await bus.execute(CloseSession(session=session))
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,112 @@
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import timedelta
|
||||
|
||||
from dishka import Provider, Scope, provide
|
||||
from redis.asyncio import Redis
|
||||
from redis.asyncio.retry import Retry
|
||||
from redis.backoff import NoBackoff
|
||||
|
||||
from messenger.identity.application.bus import IdentityCommandBus
|
||||
from messenger.identity.application.commands import CloseSession, OpenSession, RegisterUser
|
||||
from messenger.identity.application.handlers import (
|
||||
CloseSessionHandler,
|
||||
OpenSessionHandler,
|
||||
RegisterUserHandler,
|
||||
)
|
||||
from messenger.identity.application.ports import (
|
||||
IdentityUnitOfWork,
|
||||
PasswordHasher,
|
||||
SessionDirectory,
|
||||
UserDirectory,
|
||||
)
|
||||
from messenger.identity.application.queries import Authenticate, GetCurrentUser, VerifyCredentials
|
||||
from messenger.identity.config import IdentitySettings
|
||||
from messenger.identity.infrastructure.argon2 import Argon2PasswordHasher
|
||||
from messenger.identity.infrastructure.postgres import (
|
||||
PostgresIdentityUnitOfWork,
|
||||
PostgresSessionDirectory,
|
||||
PostgresUserDirectory,
|
||||
)
|
||||
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
|
||||
from messenger.shared.application.commands import Command
|
||||
from messenger.shared.application.messagebus import CommandHandler
|
||||
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger
|
||||
from messenger.shared.infrastructure.postgres import Database
|
||||
|
||||
|
||||
class IdentityProvider(Provider):
|
||||
def __init__(self, settings: IdentitySettings) -> None:
|
||||
super().__init__()
|
||||
self._settings = settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def settings(self) -> IdentitySettings:
|
||||
return self._settings
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def hasher(self, settings: IdentitySettings) -> PasswordHasher:
|
||||
return Argon2PasswordHasher(settings.password_hash_concurrency)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def users(self, database: Database) -> UserDirectory:
|
||||
return PostgresUserDirectory(database)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
async def sessions(
|
||||
self, database: Database, settings: IdentitySettings, logger: Logger
|
||||
) -> AsyncIterator[SessionDirectory]:
|
||||
origin = PostgresSessionDirectory(database)
|
||||
if settings.cache_url is None:
|
||||
yield origin
|
||||
return
|
||||
client = Redis.from_url(
|
||||
settings.cache_url.get_secret_value(),
|
||||
socket_connect_timeout=settings.cache_timeout_seconds,
|
||||
socket_timeout=settings.cache_timeout_seconds,
|
||||
retry=Retry(NoBackoff(), 1),
|
||||
)
|
||||
try:
|
||||
yield CachedSessionDirectory(
|
||||
origin,
|
||||
client,
|
||||
logger,
|
||||
limit=timedelta(seconds=settings.session_cache_ttl_seconds),
|
||||
cooldown=settings.cache_cooldown_seconds,
|
||||
)
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def verify(self, users: UserDirectory, hasher: PasswordHasher) -> VerifyCredentials:
|
||||
return VerifyCredentials(users, hasher)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def authenticate(self, sessions: SessionDirectory, clock: Clock) -> Authenticate:
|
||||
return Authenticate(sessions, clock)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def unit_of_work(self, database: Database) -> IdentityUnitOfWork:
|
||||
return PostgresIdentityUnitOfWork(database)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def current_user(self, users: UserDirectory) -> GetCurrentUser:
|
||||
return GetCurrentUser(users)
|
||||
|
||||
@provide(scope=Scope.REQUEST)
|
||||
def command_bus(
|
||||
self,
|
||||
uow: IdentityUnitOfWork,
|
||||
publisher: EventPublisher,
|
||||
clock: Clock,
|
||||
ids: IdGenerator,
|
||||
hasher: PasswordHasher,
|
||||
sessions: SessionDirectory,
|
||||
settings: IdentitySettings,
|
||||
) -> IdentityCommandBus:
|
||||
ttl = timedelta(seconds=settings.session_ttl_seconds)
|
||||
handlers: dict[type[Command], CommandHandler] = {
|
||||
RegisterUser: RegisterUserHandler(uow, clock, ids, hasher),
|
||||
OpenSession: OpenSessionHandler(uow, clock, ttl),
|
||||
CloseSession: CloseSessionHandler(uow, sessions),
|
||||
}
|
||||
return IdentityCommandBus(handlers, uow, publisher)
|
||||
@@ -0,0 +1,20 @@
|
||||
from messenger.identity.domain.events import SessionClosed, SessionOpened, UserRegistered
|
||||
from messenger.shared.application.ports import Logger
|
||||
|
||||
LOG_FIELDS = frozenset({"actor_id"})
|
||||
|
||||
|
||||
class IdentityJournal:
|
||||
__slots__ = ("_logger",)
|
||||
|
||||
def __init__(self, logger: Logger) -> None:
|
||||
self._logger = logger
|
||||
|
||||
async def on_user_registered(self, event: UserRegistered) -> None:
|
||||
self._logger.info("audit.user_registered", actor_id=str(event.user_id))
|
||||
|
||||
async def on_session_opened(self, event: SessionOpened) -> None:
|
||||
self._logger.info("audit.session_opened", actor_id=str(event.user_id))
|
||||
|
||||
async def on_session_closed(self, event: SessionClosed) -> None:
|
||||
self._logger.info("audit.session_closed", actor_id=str(event.user_id))
|
||||
@@ -0,0 +1,42 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from messenger.identity.domain.models import Session, User
|
||||
|
||||
|
||||
class CreateUserRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
username: str
|
||||
display_name: str
|
||||
password: str
|
||||
|
||||
|
||||
class UserOut(BaseModel):
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
@classmethod
|
||||
def of(cls, user: User) -> UserOut:
|
||||
return cls(
|
||||
id=user.id,
|
||||
username=user.username.value,
|
||||
display_name=user.display_name.value,
|
||||
created_at=user.created_at,
|
||||
)
|
||||
|
||||
|
||||
class SessionOut(BaseModel):
|
||||
token: str
|
||||
token_type: Literal["Bearer"] = "Bearer"
|
||||
expires_at: datetime
|
||||
user: UserOut
|
||||
|
||||
@classmethod
|
||||
def of(cls, token: str, session: Session, user: User) -> SessionOut:
|
||||
return cls(token=token, expires_at=session.expires_at, user=UserOut.of(user))
|
||||
Reference in New Issue
Block a user