From 7f8bcfd234bc610b3a0536693f0af91913a6e90f Mon Sep 17 00:00:00 2001 From: casablanca Date: Wed, 7 Oct 2026 23:18:23 +0300 Subject: [PATCH] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=B0=D1=83=D1=82=D0=B5=D0=BD=D1=82=D0=B8=D1=84?= =?UTF-8?q?=D0=B8=D0=BA=D0=B0=D1=86=D0=B8=D1=8F=20=D0=B8=20=D1=81=D0=B5?= =?UTF-8?q?=D1=81=D1=81=D0=B8=D0=B8=20=D0=B2=20redis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 2 +- compose.yaml | 35 +++++- requirements.txt | 3 + src/errors.py | 11 +- src/main.py | 252 +++++++++++++++++++++++++------------------- src/models.py | 12 +++ src/repositories.py | 112 ++++++++++++++++++++ src/security.py | 16 +++ src/sessions.py | 60 +++++++++++ 9 files changed, 389 insertions(+), 114 deletions(-) create mode 100644 src/repositories.py create mode 100644 src/security.py create mode 100644 src/sessions.py diff --git a/.env.example b/.env.example index 714c8076..c3822416 100644 --- a/.env.example +++ b/.env.example @@ -7,5 +7,5 @@ SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url # Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres +SESSION_STORE=redis CACHE_URL_FILE=/run/secrets/cache_url diff --git a/compose.yaml b/compose.yaml index 7dd1c2d4..9a4a3c33 100644 --- a/compose.yaml +++ b/compose.yaml @@ -16,23 +16,56 @@ services: retries: 10 start_period: 5s + redis: + image: redis:8.2.2 + command: + - redis-server + - --appendonly + - "yes" + - --appendfsync + - everysec + volumes: + - redis_data:/data + healthcheck: + test: [ "CMD", "redis-cli", "ping" ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + api: build: context: . dockerfile: Dockerfile + environment: + APP_HOST: ${APP_HOST:-0.0.0.0} + APP_PORT: ${APP_PORT:-8080} + APP_ENV: ${APP_ENV:-lab} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url} + SESSION_STORE: ${SESSION_STORE:-redis} + CACHE_URL_FILE: ${CACHE_URL_FILE:-/run/secrets/cache_url} secrets: - database_url + - cache_url depends_on: postgres: condition: service_healthy + redis: + condition: service_healthy ports: - "8080:8080" secrets: postgres_password: file: ./secrets/postgres_password + database_url: file: ./secrets/database_url + cache_url: + file: ./secrets/cache_url + volumes: - postgres_data: \ No newline at end of file + postgres_data: + redis_data: \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index b43dccad..2f27f572 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,3 +15,6 @@ SQLAlchemy==2.1.4 asyncpg==0.32.0 alembic==1.20.0 greenlet==3.5.6 + +argon2-cffi==25.1.0 +redis==7.0.1 diff --git a/src/errors.py b/src/errors.py index 3b3520cf..8b853205 100644 --- a/src/errors.py +++ b/src/errors.py @@ -1,5 +1,12 @@ class APIError(Exception): - def __init__(self, status_code: int, code: str, message: str): + def __init__( + self, + status_code: int, + code: str, + message: str, + headers: dict[str, str] | None = None, + ): self.status_code = status_code self.code = code - self.message = message \ No newline at end of file + self.message = message + self.headers = headers \ No newline at end of file diff --git a/src/main.py b/src/main.py index 181541ea..53cbd00a 100644 --- a/src/main.py +++ b/src/main.py @@ -1,18 +1,80 @@ -from uuid import UUID, uuid4 +from datetime import datetime, timedelta, timezone +from uuid import uuid4 -from fastapi import Depends, FastAPI, Header, Request +from fastapi import Depends, FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse +from fastapi.security import ( + HTTPAuthorizationCredentials, + HTTPBasic, + HTTPBasicCredentials, + HTTPBearer, +) +from sqlalchemy.exc import IntegrityError +from sqlalchemy.ext.asyncio import AsyncSession from starlette.exceptions import HTTPException as StarletteHTTPException +from src.database import get_db_session from src.errors import APIError -from src.models import Chat, ChatPage, CreateChat, CreateMessage, CreateUser, Message, MessagePage, User -from src.store import Store, UsernameAlreadyExistsError +from src.models import CreateUser, SessionResponse, User +from src.repositories import ( + create_user as create_user_in_db, + get_user_by_id, + get_user_credentials_by_username, +) +from src.security import verify_password +from src.sessions import ( + create_session, + delete_session, + get_session_user_id, +) app = FastAPI() -store = Store() +basic_security = HTTPBasic(auto_error=False) +bearer_security = HTTPBearer(auto_error=False) + + +async def get_current_user( + credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security), + session: AsyncSession = Depends(get_db_session), +) -> User: + if credentials is None or credentials.scheme.lower() != "bearer": + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + "WWW-Authenticate": "Bearer", + }, + ) + + user_id = await get_session_user_id(credentials.credentials) + + if user_id is None: + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + "WWW-Authenticate": "Bearer", + }, + ) + + user = await get_user_by_id(session, user_id) + + if user is None: + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + "WWW-Authenticate": "Bearer", + }, + ) + + return user @app.middleware("http") @@ -80,6 +142,7 @@ async def api_error_handler(request: Request, exc: APIError): "request_id": request_id, } }, + headers=exc.headers, ) @@ -129,37 +192,6 @@ async def unexpected_exception_handler( ) -async def get_current_user( - x_user_id: str | None = Header(default=None), -) -> User: - if x_user_id is None: - raise APIError( - status_code=401, - code="unauthorized", - message="Unauthorized", - ) - - try: - user_id = UUID(x_user_id) - except ValueError: - raise APIError( - status_code=401, - code="unauthorized", - message="Unauthorized", - ) - - user = await store.get_user(user_id) - - if user is None: - raise APIError( - status_code=401, - code="unauthorized", - message="Unauthorized", - ) - - return user - - @app.get("/health/live") async def health_live(): return {"status": "ok"} @@ -171,15 +203,20 @@ async def health_ready(): @app.post("/api/v1/users", response_model=User, status_code=201) -async def create_user(data: CreateUser): +async def create_user( + data: CreateUser, + session: AsyncSession = Depends(get_db_session), +): try: - return await store.create_user(data) - except UsernameAlreadyExistsError: + async with session.begin(): + return await create_user_in_db(session, data) + + except IntegrityError as exc: raise APIError( status_code=409, code="conflict", message="Username already exists", - ) + ) from exc @app.get("/api/v1/users/me", response_model=User) @@ -189,83 +226,78 @@ async def get_me( return current_user -@app.post("/api/v1/chats", response_model=Chat, status_code=201) -async def create_chat( - data: CreateChat, - current_user: User = Depends(get_current_user), -): - return await store.create_chat( - data=data, - current_user_id=current_user.id, - ) - - -@app.get("/api/v1/chats/{chat_id}", response_model=Chat) -async def get_chat( - chat_id: UUID, - current_user: User = Depends(get_current_user), -): - return await store.get_chat( - chat_id=chat_id, - current_user_id=current_user.id, - ) - - -@app.get("/api/v1/chats", response_model=ChatPage) -async def get_chats( - limit: int = 50, - current_user: User = Depends(get_current_user), -): - if limit < 1 or limit > 100: - raise APIError( - status_code=400, - code="invalid_request", - message="Limit must be between 1 and 100", - ) - - return await store.get_chats( - current_user_id=current_user.id, - limit=limit, - ) - - @app.post( - "/api/v1/chats/{chat_id}/messages", - response_model=Message, + "/api/v1/auth/sessions", + response_model=SessionResponse, status_code=201, ) -async def create_message( - chat_id: UUID, - data: CreateMessage, - current_user: User = Depends(get_current_user), +async def create_auth_session( + credentials: HTTPBasicCredentials | None = Depends(basic_security), + session: AsyncSession = Depends(get_db_session), ): - return await store.create_message( - chat_id=chat_id, - current_user_id=current_user.id, - data=data, + if credentials is None: + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + "WWW-Authenticate": 'Basic realm="messenger"', + }, + ) + + user_credentials = await get_user_credentials_by_username( + session, + credentials.username, + ) + + if user_credentials is None: + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + "WWW-Authenticate": 'Basic realm="messenger"', + }, + ) + + if not verify_password( + user_credentials.password_hash, + credentials.password, + ): + raise APIError( + status_code=401, + code="unauthorized", + message="Unauthorized", + headers={ + "WWW-Authenticate": 'Basic realm="messenger"', + }, + ) + + user = User( + id=user_credentials.id, + username=user_credentials.username, + display_name=user_credentials.display_name, + created_at=user_credentials.created_at, + ) + + token, ttl = await create_session(user.id) + + expires_at = datetime.now(timezone.utc) + timedelta(seconds=ttl) + + return SessionResponse( + token=token, + token_type="bearer", + expires_at=expires_at, + user=user, ) -@app.get( - "/api/v1/chats/{chat_id}/messages", - response_model=MessagePage, +@app.delete( + "/api/v1/auth/sessions/current", + status_code=204, ) -async def get_messages( - chat_id: UUID, - limit: int = 50, - cursor: str | None = None, +async def delete_current_session( + credentials: HTTPAuthorizationCredentials | None = Depends(bearer_security), current_user: User = Depends(get_current_user), ): - if limit < 1 or limit > 100: - raise APIError( - status_code=400, - code="invalid_request", - message="Limit must be between 1 and 100", - ) - - return await store.get_messages( - chat_id=chat_id, - current_user_id=current_user.id, - limit=limit, - cursor=cursor, - ) \ No newline at end of file + await delete_session(credentials.credentials) \ No newline at end of file diff --git a/src/models.py b/src/models.py index 772d6763..5f2c2991 100644 --- a/src/models.py +++ b/src/models.py @@ -18,6 +18,11 @@ class CreateUser(BaseModel): max_length=100, ) + password: str = Field( + min_length=12, + max_length=128, + ) + @field_validator("display_name") @classmethod def validate_display_name(cls, value: str) -> str: @@ -34,6 +39,13 @@ class User(BaseModel): created_at: datetime +class SessionResponse(BaseModel): + token: str + token_type: str + expires_at: datetime + user: User + + class CreateChat(BaseModel): model_config = ConfigDict(extra="forbid") diff --git a/src/repositories.py b/src/repositories.py new file mode 100644 index 00000000..78c35ee3 --- /dev/null +++ b/src/repositories.py @@ -0,0 +1,112 @@ +from uuid import UUID, uuid4 + +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from src.models import CreateUser, User +from src.security import hash_password + + +async def create_user( + session: AsyncSession, + data: CreateUser, +) -> User: + user_id = uuid4() + password_hash = hash_password(data.password) + + result = await session.execute( + text( + """ + INSERT INTO users ( + id, + username, + display_name, + password_hash + ) + VALUES ( + :id, + :username, + :display_name, + :password_hash + ) + RETURNING + id, + username, + display_name, + created_at + """ + ), + { + "id": user_id, + "username": data.username, + "display_name": data.display_name, + "password_hash": password_hash, + }, + ) + + row = result.one() + + return User( + id=UUID(str(row.id)), + username=row.username, + display_name=row.display_name, + created_at=row.created_at, + ) + +async def get_user_credentials_by_username( + session: AsyncSession, + username: str, +): + result = await session.execute( + text( + """ + SELECT + id, + username, + display_name, + password_hash, + created_at + FROM users + WHERE username = :username + """ + ), + { + "username": username, + }, + ) + + return result.one_or_none() + + +async def get_user_by_id( + session: AsyncSession, + user_id: UUID, +) -> User | None: + result = await session.execute( + text( + """ + SELECT + id, + username, + display_name, + created_at + FROM users + WHERE id = :user_id + """ + ), + { + "user_id": user_id, + }, + ) + + row = result.one_or_none() + + if row is None: + return None + + return User( + id=UUID(str(row.id)), + username=row.username, + display_name=row.display_name, + created_at=row.created_at, + ) \ No newline at end of file diff --git a/src/security.py b/src/security.py new file mode 100644 index 00000000..0afbbf1a --- /dev/null +++ b/src/security.py @@ -0,0 +1,16 @@ +from argon2 import PasswordHasher +from argon2.exceptions import VerifyMismatchError + + +password_hasher = PasswordHasher() + + +def hash_password(password: str) -> str: + return password_hasher.hash(password) + + +def verify_password(password_hash: str, password: str) -> bool: + try: + return password_hasher.verify(password_hash, password) + except VerifyMismatchError: + return False \ No newline at end of file diff --git a/src/sessions.py b/src/sessions.py new file mode 100644 index 00000000..4174442c --- /dev/null +++ b/src/sessions.py @@ -0,0 +1,60 @@ +import os +import secrets +from uuid import UUID + +from redis.asyncio import Redis + + +CACHE_URL_FILE = "/run/secrets/cache_url" +DEFAULT_SESSION_TTL_SECONDS = 3600 + + +def read_cache_url() -> str: + with open(CACHE_URL_FILE, encoding="utf-8") as file: + return file.read().strip() + + +def get_session_ttl_seconds() -> int: + return int( + os.getenv( + "SESSION_TTL_SECONDS", + str(DEFAULT_SESSION_TTL_SECONDS), + ) + ) + + +redis_client = Redis.from_url( + read_cache_url(), + decode_responses=True, + socket_connect_timeout=5, + socket_timeout=5, +) + + +async def create_session(user_id: UUID) -> tuple[str, int]: + token = secrets.token_urlsafe(32) + ttl = get_session_ttl_seconds() + + await redis_client.set( + f"session:{token}", + str(user_id), + ex=ttl, + ) + + return token, ttl + + +async def get_session_user_id(token: str) -> UUID | None: + value = await redis_client.get(f"session:{token}") + + if value is None: + return None + + try: + return UUID(value) + except ValueError: + return None + + +async def delete_session(token: str) -> None: + await redis_client.delete(f"session:{token}") \ No newline at end of file