diff --git a/app/auth.py b/app/auth.py index 4983698..3ca76bb 100644 --- a/app/auth.py +++ b/app/auth.py @@ -11,6 +11,10 @@ from sqlalchemy.ext.asyncio import AsyncSession from .db.models import SessionRow, User from .db.session import get_db +import redis.asyncio as redis + +redis_client = redis.from_url(os.getenv("REDIS_URL", "redis://redis:6379/0")) + SESSION_TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600")) @@ -46,6 +50,14 @@ def _unauthorized_bearer() -> HTTPException: ) +async def create_session(user_id: str) -> str: + token = generate_token() + await redis_client.setex( + f"session:{hash_token(token)}", SESSION_TTL, str(user_id) + ) + return token + + async def get_current_user( authorization: str | None = Header(None, alias="Authorization"), db: AsyncSession = Depends(get_db), @@ -54,15 +66,10 @@ async def get_current_user( raise _unauthorized_bearer() token = authorization[7:] token_hash = hash_token(token) - now = datetime.now(timezone.utc) - stmt = select(SessionRow).where( - SessionRow.token_hash == token_hash, - SessionRow.expires_at > now, - ) - session = (await db.execute(stmt)).scalar_one_or_none() - if session is None: + user_id_raw = await redis_client.get(f"session:{token_hash}") + if user_id_raw is None: raise _unauthorized_bearer() - user = await db.get(User, session.user_id) + user = await db.get(User, UUID(user_id_raw.decode())) if user is None: raise _unauthorized_bearer() return user @@ -72,9 +79,4 @@ async def revoke_current_session(authorization: str, db: AsyncSession) -> None: if not authorization or not authorization.startswith("Bearer "): raise _unauthorized_bearer() token = authorization[7:] - result = await db.execute( - delete(SessionRow).where(SessionRow.token_hash == hash_token(token)) - ) - await db.commit() - if result.rowcount == 0: - raise _unauthorized_bearer() \ No newline at end of file + await redis_client.delete(f"session:{hash_token(token)}") \ No newline at end of file diff --git a/app/main.py b/app/main.py index 35f239f..7fc0224 100644 --- a/app/main.py +++ b/app/main.py @@ -15,6 +15,7 @@ from starlette.middleware.base import BaseHTTPMiddleware from .auth import ( SESSION_TTL, + create_session, generate_token, get_current_user, hash_password, @@ -172,9 +173,7 @@ async def login( ) token = generate_token() expires = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL) - db.add( - SessionRow(user_id=user.id, token_hash=hash_token(token), expires_at=expires) - ) + token = await create_session(str(user.id)) await db.commit() return { "token": token, diff --git a/evidence/explain_messages.txt b/evidence/explain_messages.txt new file mode 100644 index 0000000..6761ebb Binary files /dev/null and b/evidence/explain_messages.txt differ diff --git a/evidence/explain_messages_no_index.txt b/evidence/explain_messages_no_index.txt new file mode 100644 index 0000000..89abff4 Binary files /dev/null and b/evidence/explain_messages_no_index.txt differ diff --git a/evidence/session_expiry.txt b/evidence/session_expiry.txt new file mode 100644 index 0000000..9b9d330 Binary files /dev/null and b/evidence/session_expiry.txt differ diff --git a/scripts/seed_10k.py b/scripts/seed_10k.py new file mode 100644 index 0000000..9017c13 --- /dev/null +++ b/scripts/seed_10k.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Заполняет чат 10 000 сообщениями через urllib (httpx не работает через docker-proxy на Windows).""" +import json +import base64 +import uuid +import urllib.request +import urllib.error + +BASE = "http://127.0.0.1:8080" +PASSWORD = "Example-only-not-a-real-secret-123" + + +def call(method, path, body=None, token=None, raw_body=None, content_type=None): + h = {"Accept": "application/json"} + if token: + h["Authorization"] = f"Bearer {token}" + data = None + if raw_body is not None: + data = raw_body + h["Content-Type"] = content_type or "application/json" + elif body is not None: + data = json.dumps(body).encode("utf-8") + h["Content-Type"] = "application/json" + req = urllib.request.Request(BASE + path, data=data, headers=h, method=method) + try: + with urllib.request.urlopen(req, timeout=60) as r: + payload = r.read() + return r.status, (json.loads(payload) if payload else None) + except urllib.error.HTTPError as e: + payload = e.read() + try: + return e.code, (json.loads(payload) if payload else None) + except ValueError: + return e.code, None + + +def main(): + name = f"seeder_{uuid.uuid4().hex[:6]}" + + # 1) пользователь + s, u = call("POST", "/api/v1/users", + {"username": name, "display_name": name, "password": PASSWORD}) + assert s == 201, f"create user: {s} {u}" + + # 2) сессия через Basic + cred = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode() + req = urllib.request.Request( + BASE + "/api/v1/auth/sessions", + method="POST", + headers={"Authorization": f"Basic {cred}", "Accept": "application/json"}, + ) + with urllib.request.urlopen(req, timeout=30) as r: + session = json.loads(r.read()) + token = session["token"] + + # 3) чат + s, chat = call("POST", "/api/v1/chats", + {"title": "seed", "member_ids": [u["id"]]}, token=token) + assert s == 201, f"create chat: {s} {chat}" + cid = chat["id"] + print("chat_id =", cid, flush=True) + + # 4) 10 000 сообщений + for i in range(10000): + s, _ = call("POST", f"/api/v1/chats/{cid}/messages", + {"text": f"m{i}"}, token=token) + if s != 201: + print(f"failed at {i}: {s}") + break + if (i + 1) % 1000 == 0: + print(f" {i + 1}/10000", flush=True) + + print("DONE") + print("chat_id =", cid) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/test_expiry.py b/scripts/test_expiry.py new file mode 100644 index 0000000..9f82c87 --- /dev/null +++ b/scripts/test_expiry.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +import base64 +import json +import time +import urllib.request +import urllib.error +import uuid + +BASE = "http://127.0.0.1:8080" +PASSWORD = "Example-only-not-a-real-secret-123" + + +def call(method, path, body=None, token=None, basic=None): + h = {"Accept": "application/json"} + if token: + h["Authorization"] = f"Bearer {token}" + if basic: + h["Authorization"] = f"Basic {basic}" + data = None + if body is not None: + data = json.dumps(body).encode("utf-8") + h["Content-Type"] = "application/json" + req = urllib.request.Request(BASE + path, data=data, headers=h, method=method) + try: + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, json.loads(r.read()) if r.status != 204 else None + except urllib.error.HTTPError as e: + payload = e.read() + try: + return e.code, json.loads(payload) if payload else None + except ValueError: + return e.code, None + + +name = f"exp_{uuid.uuid4().hex[:6]}" +s, _ = call("POST", "/api/v1/users", {"username": name, "display_name": name, "password": PASSWORD}) +assert s == 201, s + +cred = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode() +s, session = call("POST", "/api/v1/auth/sessions", basic=cred) +assert s == 201, (s, session) +token = session["token"] +print(f"session created, expires_at={session['expires_at']}") + +# Сразу +s, _ = call("GET", "/api/v1/users/me", token=token) +print(f"immediately: {s} (expect 200)") + +# Ждём 4 секунды (TTL=2s) +time.sleep(4) + +s, body = call("GET", "/api/v1/users/me", token=token) +print(f"after 4s: {s} (expect 401)") +print(f"body: {body}") \ No newline at end of file