Files

51 lines
2.2 KiB
Python

#!/usr/bin/env python3
"""Истечение сессии при коротком SESSION_TTL_SECONDS (экземпляр api-ttl, профиль compose `ttl`).
Проверяет и путь через кэш Redis (запись кэша прогрета сразу после входа), и путь через PostgreSQL:
TTL записи в кэше = min(SESSION_CACHE_TTL_SECONDS, остаток сессии), поэтому кэш не продлевает сессию.
"""
import datetime as dt
import time
from common import TTL_BASE_URL, TTL_SECONDS, Client, Suite, check, login, new_user, sql
c = Client(TTL_BASE_URL)
s = Suite("session expiry, SESSION_TTL_SECONDS=%g (%s)" % (TTL_SECONDS, TTL_BASE_URL))
@s.case("expires_at = now + SESSION_TTL_SECONDS")
def _():
u = new_user(c, "ttl"); login(c, u)
left = dt.datetime.fromisoformat(u["expires_at"][:-1] + "+00:00") - dt.datetime.now(dt.timezone.utc)
check(0 < left.total_seconds() <= TTL_SECONDS + 0.5, "unexpected TTL: %s" % left)
return "remaining %.2fs" % left.total_seconds()
@s.case("token valid before expiry, 401 Bearer after (cache warmed)")
def _():
u = new_user(c, "ttl2"); login(c, u)
c.call("GET", "/api/v1/users/me", actor=u, schema="User") # заполняет кэш
c.call("GET", "/api/v1/chats", actor=u, schema="ChatPage")
time.sleep(TTL_SECONDS + 1.0)
r = c.call("GET", "/api/v1/users/me", 401, actor=u)
check(r["headers"]["WWW-Authenticate"].startswith("Bearer"), "challenge")
c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=u)
rows = sql("SELECT (expires_at < clock_timestamp())::text, (revoked_at IS NULL)::text FROM sessions s"
" JOIN users u ON u.id = s.user_id WHERE u.username = '%s'" % u["username"])
check(rows == ["true|true"], "expiry must come from expires_at, not deletion/revocation: %s" % rows)
@s.case("re-login after expiry issues a new valid session")
def _():
u = new_user(c, "ttl3"); login(c, u)
old = u["token"]
time.sleep(TTL_SECONDS + 1.0)
c.call("GET", "/api/v1/users/me", 401, actor=u)
login(c, u)
check(u["token"] != old, "token reused")
c.call("GET", "/api/v1/users/me", actor=u, schema="User")
if __name__ == "__main__":
s.run()