Files
mtusi2026labs/src/messenger/identity/entrypoints/authentication.py
T
ArtyomandClaude Opus 5.5 416ce4f9db 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>
2026-10-28 11:26:15 +03:00

99 lines
3.3 KiB
Python

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)]