forked from mtusi2026/mtusi2026lab7
feat: completed tasks for grade 4
This commit is contained in:
@@ -47,6 +47,7 @@ class Settings(BaseSettings):
|
||||
|
||||
max_messages: int = Field(ge=1)
|
||||
max_in_flight: int = Field(ge=1)
|
||||
login_max_in_flight: int = Field(default=10, ge=1, le=16)
|
||||
|
||||
session_ttl_seconds: int = Field(default=3600, ge=1)
|
||||
session_store: Literal["redis"] = "redis"
|
||||
|
||||
+3
-4
@@ -1,6 +1,5 @@
|
||||
"""Настройки очереди из .env; credentials брокера читаются отдельно из файла."""
|
||||
"""Настройки очереди из .env; идентификация брокера через TLS."""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Self
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
@@ -13,9 +12,9 @@ class JobSettings(BaseSettings):
|
||||
broker_ca_file: str | None = None
|
||||
broker_host: str = "broker"
|
||||
broker_port: int = Field(default=5672, ge=1, le=65535)
|
||||
broker_password_file: Path = Path("/run/secrets/broker_password")
|
||||
broker_cert_file: str = "/run/tls/broker-client.crt"
|
||||
broker_key_file: str = "/run/tls/broker-client.key"
|
||||
broker_queue: str = "attachment-jobs"
|
||||
broker_user: str = "messenger"
|
||||
broker_vhost: str = "/"
|
||||
worker_concurrency: int = Field(default=2, ge=1, le=4)
|
||||
job_max_attempts: int = Field(default=5, ge=1, le=100)
|
||||
|
||||
@@ -40,3 +40,13 @@ async def acquire_request_slot(request: Request) -> AsyncIterator[None]:
|
||||
yield
|
||||
finally:
|
||||
capacity.release()
|
||||
|
||||
|
||||
async def acquire_login_slot(request: Request) -> AsyncIterator[None]:
|
||||
capacity: RequestCapacity = request.app.state.login_capacity
|
||||
if not capacity.try_acquire():
|
||||
raise rate_limited()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
capacity.release()
|
||||
|
||||
@@ -48,6 +48,10 @@ async def verify_password(password: str, password_hash: str) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def password_needs_rehash(password_hash: str) -> bool:
|
||||
return _hasher.check_needs_rehash(password_hash)
|
||||
|
||||
|
||||
async def dummy_verify_password(password: str) -> None:
|
||||
"""Проверка против фиктивного хеша: время ответа не выдаёт отсутствие пользователя."""
|
||||
await verify_password(password, _DUMMY_HASH)
|
||||
|
||||
@@ -45,6 +45,11 @@ async def create_session(
|
||||
if not await security.verify_password(password, user.password_hash):
|
||||
raise unauthorized_basic()
|
||||
|
||||
if security.password_needs_rehash(user.password_hash):
|
||||
replacement = await security.hash_password(password)
|
||||
await users_storage.replace_password_hash(session, user.id, user.password_hash, replacement)
|
||||
await session.commit()
|
||||
|
||||
token = security.generate_token()
|
||||
expires_at = datetime.now(UTC) + timedelta(seconds=ttl_seconds)
|
||||
await sessions_storage.create_session(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from fastapi import APIRouter, Response
|
||||
from fastapi import APIRouter, Depends, Response
|
||||
|
||||
from app.core.request_capacity import acquire_login_slot
|
||||
from app.domain.auth import create_session, revoke_session
|
||||
from app.endpoints.dependencies import (
|
||||
AppSettings,
|
||||
@@ -13,7 +14,7 @@ from app.schemas.session import AuthSession
|
||||
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/sessions", status_code=201)
|
||||
@router.post("/sessions", status_code=201, dependencies=[Depends(acquire_login_slot)])
|
||||
async def login(
|
||||
credentials: BasicCredentials,
|
||||
session: DbSession,
|
||||
|
||||
@@ -61,6 +61,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
application.state.upload_capacity = create_request_capacity(
|
||||
settings.s3.max_concurrent_uploads
|
||||
)
|
||||
application.state.login_capacity = create_request_capacity(settings.login_max_in_flight)
|
||||
application.state.request_capacity = create_request_capacity(settings.max_in_flight)
|
||||
application.state.instance_id = resolve_instance_id(settings.instance_id)
|
||||
telemetry = Telemetry("messenger-api", application.state.instance_id)
|
||||
|
||||
+18
-11
@@ -13,6 +13,23 @@ from app.core.tls import client_context
|
||||
from app.schemas.job import JobMessage
|
||||
|
||||
|
||||
async def connect_broker(settings: JobSettings):
|
||||
context = client_context(settings.broker_ca_file)
|
||||
if context is None:
|
||||
raise ValueError("RabbitMQ требует CA и клиентский сертификат")
|
||||
context.load_cert_chain(settings.broker_cert_file, settings.broker_key_file)
|
||||
return await aio_pika.connect(
|
||||
host=settings.broker_host,
|
||||
port=settings.broker_port,
|
||||
virtualhost=settings.broker_vhost,
|
||||
ssl=True,
|
||||
ssl_context=context,
|
||||
auth="external",
|
||||
timeout=5,
|
||||
heartbeat=30,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Delivery:
|
||||
id: AbstractIncomingMessage
|
||||
@@ -37,17 +54,7 @@ class JobBroker:
|
||||
or self.channel.is_closed
|
||||
):
|
||||
await self.aclose()
|
||||
self.connection = await aio_pika.connect(
|
||||
host=self.settings.broker_host,
|
||||
port=self.settings.broker_port,
|
||||
login=self.settings.broker_user,
|
||||
password=self.settings.broker_password_file.read_text().strip(),
|
||||
virtualhost=self.settings.broker_vhost,
|
||||
ssl=bool(self.settings.broker_ca_file),
|
||||
ssl_context=client_context(self.settings.broker_ca_file),
|
||||
timeout=5,
|
||||
heartbeat=30,
|
||||
)
|
||||
self.connection = await connect_broker(self.settings)
|
||||
self.channel = await self.connection.channel(
|
||||
publisher_confirms=True, on_return_raises=True
|
||||
)
|
||||
|
||||
+11
-1
@@ -1,7 +1,7 @@
|
||||
from collections.abc import Collection
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.user import User
|
||||
@@ -45,3 +45,13 @@ async def get_existing_user_ids(
|
||||
result = await session.execute(stmt)
|
||||
existing_ids = set(result.scalars().all())
|
||||
return existing_ids
|
||||
|
||||
|
||||
async def replace_password_hash(
|
||||
session: AsyncSession, user_id: UUID, previous: str, replacement: str
|
||||
) -> None:
|
||||
await session.execute(
|
||||
update(User)
|
||||
.where(User.id == user_id, User.password_hash == previous)
|
||||
.values(password_hash=replacement)
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user