From 2b90834d037422c1ebcfe896aa4d2147d78bfd6c Mon Sep 17 00:00:00 2001 From: Maksimova Snezhana Date: Thu, 1 Oct 2026 03:14:07 +0300 Subject: [PATCH] =?UTF-8?q?EXPLAIN=20=D0=BD=D0=B0=208837=20=D1=81=D0=BE?= =?UTF-8?q?=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8=D1=8F=D1=85=20=D0=B8=20ses?= =?UTF-8?q?sion=20expiry?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/auth.py | 30 +++++----- app/main.py | 5 +- evidence/explain_messages.txt | Bin 0 -> 1558 bytes evidence/explain_messages_no_index.txt | Bin 0 -> 1992 bytes evidence/session_expiry.txt | Bin 0 -> 500 bytes scripts/seed_10k.py | 78 +++++++++++++++++++++++++ scripts/test_expiry.py | 54 +++++++++++++++++ 7 files changed, 150 insertions(+), 17 deletions(-) create mode 100644 evidence/explain_messages.txt create mode 100644 evidence/explain_messages_no_index.txt create mode 100644 evidence/session_expiry.txt create mode 100644 scripts/seed_10k.py create mode 100644 scripts/test_expiry.py 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 0000000000000000000000000000000000000000..6761ebb6d19c5a6ba66cfe0d61a33be1096bda9d GIT binary patch literal 1558 zcmeH{OHaa35QWd$#Q$)2;G(3JrzDuDVPRqnz80CeyiiNpp zJ2Ra*GjnFz&kv_VId^(eQ}=qNqLyxSq1%J0&FNT23jWVt3>a6A3BGE~HS<%s2z};r#4F4YB*QNF zyJ@u_a7W~s>dj{|)U;ar3NFDNaAImnRL7E#y@M80i9@z-8sKhX0-f{5=~@$fVl9y$ zsIi0Yz)OgkXozgxEY*gS7;A#Z&`WK+Ez68|J)g^D%h>iYj%p2SJI=E1Vzo+*MR+Lb z46hBdRnL1F+h5p?z}v7JZDFTV+s$tFKa*wa%J7488Xmbtn}Wpu07cEFwyeRuKCk)_U5=APN??6cMVb`M(YqRo4BekFh45tiu#U=qn_$X@ Gp?v`%iMibX literal 0 HcmV?d00001 diff --git a/evidence/explain_messages_no_index.txt b/evidence/explain_messages_no_index.txt new file mode 100644 index 0000000000000000000000000000000000000000..89abff400e8727cc843ae161e89335ca2ea1b556 GIT binary patch literal 1992 zcmd^=OK;Oa6otBbcLMMrHCYk#-;G*3*Wtim?14v z$fBESWP8TGb06oNJN|idtV5mXu^uVTGTq;Jr}tzq(J3*H^jgpL_8y~KomPAIK@F=o z1M5#(aJ7ziM>92Av3jbZ`pVVQo(k^0KkJbO*j{3HjiuS;tgrEL#=Z;Q*p4T>>!`wC zt1F&!)~&~?u`rJ%I|uGLtZdh9zjNX=`r?tyYslIddx76`Molg&jd`;odc~?HlZ?4l zWw8n}iu<~H#@7s`H`s1c_W&e%8ZpxR_O*}SKJT`xy-aE!;wkkVF#UJ!X=lbdUQziE zM`GqER8(hJd;pbJyF@UKA`*9ddBYy#vBB0*Z5{uvcjN`%DrX~NXZ8!nGQ=)n_A~6< z9cNqC(p)2hwZ4+!F)FLHWY+k7K}IV^rH?+dy{WQI)wyfC2Y-FAw`Yk}RQ0y(2HyqR zww?+7W1Y0_yL2^e#&BBuOE{c6ub0k_)n%%0VcFQtP<*Bx9T0m&7D4?(PPTKt&bW8! zx;@5#S%pQVDKqQEf-46Hdluw8#eRn<21y{G+`W|ht-uwW-c#(5r;@r|ctHbtG8 z)+?}BX@91^()s@=C;zR!Bd{`MEXjU}8peq#H}_{q1~sqy%lK>B`B^&`#`XvVjqL>p qgguA)&i5Gz+W8k0n(hjx-vOsd+|_XoqGkf_=5NA(GXA6gUi|{A4)S;a literal 0 HcmV?d00001 diff --git a/evidence/session_expiry.txt b/evidence/session_expiry.txt new file mode 100644 index 0000000000000000000000000000000000000000..9b9d3302e3d2b733112d00d76bfaba4f9d8efe6a GIT binary patch literal 500 zcmaix-Acqj4293N;5+QyD7eyY>#`Mm3%&71X1B9iP*>Xu{@|;tUosUG1PMtqCz&(J z>F39wqyg)+)4gWes0WD}iLH)6lAiTI-S9zIUOUr51-{f=CD|M=bxtgFN>&jo)jGyc z$QtmKF14>cnC>uR@1}Qd^+NybhZ%dp`CxiIG1tgB>)Jr(qlKNfQ$EgjSI_>c%@ez4}JM6$`$fsTy?+o_T^U{<&oe yKf-D{k0{+S*Z18@Yqo6hgrY6XOQM|{@&(l`i2b?9v=wTv_%`$=zZdk5nf_n!R!hhL literal 0 HcmV?d00001 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