forked from mtusi2026/mtusi2026lab5
Carry over the lab 4 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack, HAProxy, k6 and RustFS configuration, migrations, hooks, evidence and scenario scripts and the CI job from the lab 4 solution commit d2744bc, merge the lab 4 Makefile targets into the lab 5 skeleton Makefile without touching its targets, and append the lab 4 solution variables to the skeleton .env.example. The package and the application follow the contract version 1.5.0, and the image and the throwaway test containers are tagged lab5 so they do not collide with a lab 4 stand on the same host. This is the starting point of the lab 5 cycle: lint, own tests and the offline skeleton check pass before any lab 5 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
1210dd899c
commit
540fcb35ba
@@ -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)]
|
||||
Reference in New Issue
Block a user